I would like to connect to a websocket via asyncio
and websockets
, with a format as shown below. How would I be able to accomplish this?
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!"
How to write async programs?
async
await
All other is almost same as with regular Python programs.
Output:
As you see, code is almost same as you wrote.
Only difference is that
websockets.connect
designed to be async context manager (it uses__aenter__
,__aexit__
). It's necessary to release connection and will also help you to make async operations during class initialization (since we have no async version of__init__
).I advise you to organize your class same way. But if you really don't want to use context manager for some reason you can use new
__await__
method to make async initialization and some other async function to release connection:Many examples of using
websockets
you can find in it's docs.