from aiohttp import web async def websocket_handler(request): ws = web.WebSocketResponse() await ws.prepare(request) async for msg in ws: if msg.type == web.WSMsgType.TEXT: await ws.send_str("You said: " + msg.data) elif msg.type == web.WSMsgType.ERROR: print('WebSocket connection closed with exception %s' % ws.exception()) return ws
async def send_messages(websocket, path): while True: message = await websocket.recv() if message is None: break print(f'Received message: {message}') await websocket.send(f'Received message: {message}') await websocket.close() app = web.Application() app.add_routes([web.get('/ws', send_messages)]) web.run_app(app, port=8080)In this example, the send_messages function is used to handle incoming WebSocket messages. It loops continuously to receive messages and sends back a response to the client for each message received. The app is then initialized and run using the web.run_app method. The aiohttp.web package library provides tools for implementing WebSocket connections in Python, allowing for real-time communication between clients and servers.