async def websocket_handler(request): ws = aiohttp.web.WebSocketResponse() await ws.prepare(request) async for message in ws: if message.type == aiohttp.WSMsgType.TEXT: print(f"Received message: {message.data}") elif message.type == aiohttp.WSMsgType.ERROR: print("Websocket connection closed with error: ", ws.exception()) else: print(f"Received unsupported message type: {message.type}") return ws
async def websocket_handler(request): ws = aiohttp.web.WebSocketResponse() await ws.prepare(request) await ws.send_str("Hello from the server!") async for message in ws: ... return wsIn this example, we set up the WebSocket connection as before, but then immediately send a message to the client using the `send_str()` method. The client will receive this message as soon as the connection is established. The `aiohttp.web` package library is used to provide WebSocket support in Python.