Python Language Asyncio Module A Simple Websocket


Here we make a simple echo websocket using asyncio. We define coroutines for connecting to a server and sending/receiving messages. The communcations of the websocket are run in a main coroutine, which is run by an event loop. This example is modified from a prior post.

import asyncio
import aiohttp

session = aiohttp.ClientSession()                          # handles the context manager
class EchoWebsocket:
    async def connect(self):
        self.websocket = await session.ws_connect("wss://")
    async def send(self, message):

    async def receive(self):
        result = (await self.websocket.receive())

async def main():
    echo = EchoWebsocket()
    await echo.connect()
    await echo.send("Hello World!")
    print(await echo.receive())                            # "Hello World!"

if __name__ == '__main__':
    # The main loop
    loop = asyncio.get_event_loop()