A Simple Websocket

suggest change

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

ClientSession must be created inside a running loop and closed, and send_str must be awaited. wss://echo.websocket.org accepted a WebSocket handshake on 16 October 2026. This aiohttp program was not executed here.

import asyncio
import aiohttp

class EchoWebsocket:
    def __init__(self, session):
        self.session = session

    async def connect(self):
        self.websocket = await self.session.ws_connect("wss://echo.websocket.org")

    async def send(self, message):
        await self.websocket.send_str(message)

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

async def main():
    async with aiohttp.ClientSession() as session:
        echo = EchoWebsocket(session)
        await echo.connect()
        await echo.send("Hello World!")
        print(await echo.receive())  # "Hello World!"
        await echo.websocket.close()

if __name__ == '__main__':
    asyncio.run(main())

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents