python - simplewebsocketserver - ¿Cómo puedo implementar asyncio websockets en una clase?
websocket python javascript (1)
¿Cómo escribir programas asíncronos?
- Debe definir funciones
async
conasync
- Deberías llamar a async funcs con await.
- Necesita un bucle de eventos para iniciar su programa asíncrono.
Todo lo demás es casi igual que con los programas regulares de Python.
import asyncio
from websockets import connect
class EchoWebsocket:
async def __aenter__(self):
self._conn = connect("wss://echo.websocket.org")
self.websocket = await self._conn.__aenter__()
return self
async def __aexit__(self, *args, **kwargs):
await self._conn.__aexit__(*args, **kwargs)
async def send(self, message):
await self.websocket.send(message)
async def receive(self):
return await self.websocket.recv()
async def main():
async with EchoWebsocket() as echo:
await echo.send("Hello!")
print(await echo.receive()) # "Hello!"
if __name__ == ''__main__'':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Salida:
Hello!
Como ves, el código es casi el mismo que escribiste.
La única diferencia es que websockets.connect
diseñado para ser un administrador de contexto asíncrono (usa __aenter__
, __aexit__
). Es necesario liberar la conexión y también lo ayudará a realizar operaciones asíncronas durante la inicialización de la clase (ya que no tenemos una versión asíncrona de __init__
).
Te aconsejo que organices tu clase de la misma manera. Pero si realmente no desea usar el administrador de contexto por alguna razón, puede usar el nuevo método __await__
para realizar la inicialización asíncrona y alguna otra función asíncrona para liberar la conexión:
import sys
import asyncio
from websockets import connect
class EchoWebsocket:
def __await__(self):
# see: http://stackoverflow.com/a/33420721/1113207
return self._async_init().__await__()
async def _async_init(self):
self._conn = connect("wss://echo.websocket.org")
self.websocket = await self._conn.__aenter__()
return self
async def close(self):
await self._conn.__aexit__(*sys.exc_info())
async def send(self, message):
await self.websocket.send(message)
async def receive(self):
return await self.websocket.recv()
async def main():
echo = await EchoWebsocket()
try:
await echo.send("Hello!")
print(await echo.receive()) # "Hello!"
finally:
await echo.close()
if __name__ == ''__main__'':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Muchos ejemplos de uso de websockets
se pueden encontrar en sus docs .
Me gustaría conectarme a un websocket a través de asyncio
y websockets
, con el formato que se muestra a continuación. ¿Cómo podría lograr esto?
from websockets import connect
class EchoWebsocket:
def __init__(self):
self.websocket = self._connect()
def _connect(self):
return connect("wss://echo.websocket.org")
def send(self, message):
self.websocket.send(message)
def receive(self):
return self.websocket.recv()
echo = EchoWebsocket()
echo.send("Hello!")
print(echo.receive()) # "Hello!"