Python Language
WebSockets
Ricerca…
Eco semplice con aiohttp
aiohttp
fornisce aiohttp
asincroni.
import asyncio
from aiohttp import ClientSession
with ClientSession() as session:
async def hello_world():
websocket = await session.ws_connect("wss://echo.websocket.org")
websocket.send_str("Hello, world!")
print("Received:", (await websocket.receive()).data)
await websocket.close()
loop = asyncio.get_event_loop()
loop.run_until_complete(hello_world())
Classe wrapper con aiohttp
aiohttp.ClientSession
può essere utilizzato come genitore per una classe WebSocket personalizzata.
import asyncio
from aiohttp import ClientSession
class EchoWebSocket(ClientSession):
URL = "wss://echo.websocket.org"
def __init__(self):
super().__init__()
self.websocket = None
async def connect(self):
"""Connect to the WebSocket."""
self.websocket = await self.ws_connect(self.URL)
async def send(self, message):
"""Send a message to the WebSocket."""
assert self.websocket is not None, "You must connect first!"
self.websocket.send_str(message)
print("Sent:", message)
async def receive(self):
"""Receive one message from the WebSocket."""
assert self.websocket is not None, "You must connect first!"
return (await self.websocket.receive()).data
async def read(self):
"""Read messages from the WebSocket."""
assert self.websocket is not None, "You must connect first!"
while self.websocket.receive():
message = await self.receive()
print("Received:", message)
if message == "Echo 9!":
break
async def send(websocket):
for n in range(10):
await websocket.send("Echo {}!".format(n))
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
with EchoWebSocket() as websocket:
loop.run_until_complete(websocket.connect())
tasks = (
send(websocket),
websocket.read()
)
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
Utilizzando Autobahn come una Websocket Factory
Il pacchetto Autobahn può essere utilizzato per le fabbriche di server socket web Python.
Documentazione del pacchetto Autobahn Python
Per installare, in genere si dovrebbe semplicemente utilizzare il comando del terminale
(Per Linux):
sudo pip install autobahn
(Per Windows):
python -m pip install autobahn
Quindi, un semplice server echo può essere creato in uno script Python:
from autobahn.asyncio.websocket import WebSocketServerProtocol
class MyServerProtocol(WebSocketServerProtocol):
'''When creating server protocol, the
user defined class inheriting the
WebSocketServerProtocol needs to override
the onMessage, onConnect, et-c events for
user specified functionality, these events
define your server's protocol, in essence'''
def onMessage(self,payload,isBinary):
'''The onMessage routine is called
when the server receives a message.
It has the required arguments payload
and the bool isBinary. The payload is the
actual contents of the "message" and isBinary
is simply a flag to let the user know that
the payload contains binary data. I typically
elsewise assume that the payload is a string.
In this example, the payload is returned to sender verbatim.'''
self.sendMessage(payload,isBinary)
if__name__=='__main__':
try:
importasyncio
except ImportError:
'''Trollius = 0.3 was renamed'''
import trollius as asyncio
from autobahn.asyncio.websocketimportWebSocketServerFactory
factory=WebSocketServerFactory()
'''Initialize the websocket factory, and set the protocol to the
above defined protocol(the class that inherits from
autobahn.asyncio.websocket.WebSocketServerProtocol)'''
factory.protocol=MyServerProtocol
'''This above line can be thought of as "binding" the methods
onConnect, onMessage, et-c that were described in the MyServerProtocol class
to the server, setting the servers functionality, ie, protocol'''
loop=asyncio.get_event_loop()
coro=loop.create_server(factory,'127.0.0.1',9000)
server=loop.run_until_complete(coro)
'''Run the server in an infinite loop'''
try:
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
server.close()
loop.close()
In questo esempio, un server viene creato sull'host locale (127.0.0.1) sulla porta 9000. Questo è l'IP e la porta di ascolto. Si tratta di informazioni importanti, in quanto utilizzando questo, è possibile identificare l'indirizzo LAN del computer e il port forwarding dal modem, indipendentemente dai router che si hanno sul computer. Quindi, utilizzando google per indagare sul tuo IP WAN, potresti progettare il tuo sito Web per inviare messaggi WebSocket al tuo indirizzo IP WAN, sulla porta 9000 (in questo esempio).
È importante eseguire il port forwarding dal tuo modem, il che significa che se hai router collegati a margherita al modem, inserisci le impostazioni di configurazione del modem, porta in avanti dal modem al router connesso e così via fino al router finale del tuo computer è collegato a sta ricevendo le informazioni ricevute sulla porta modem 9000 (in questo esempio) inoltrate ad esso.