Simple Echo with aiohttp
suggest changeaiohttp provides asynchronous websockets. aiohttp is not installed here. Current ClientSession documentation enters the session with async with, and ClientWebSocketResponse.send_str is a coroutine. This sample uses with and does not await send_str. On Python 3.14, asyncio.get_event_loop() raises RuntimeError when no loop is already running.
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())
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents