async def websocket_handler(request): ws = aiohttp.web.WebSocketResponse() await ws.prepare(request) if ws.can_prepare(): # send a message to the client await ws.send_str('Hello from the server!') return ws
async def websocket_handler(request): ws = aiohttp.web.WebSocketResponse() await ws.prepare(request) if not ws.can_prepare(): # close the WebSocket connection await ws.close() return ws async for msg in ws: # process incoming messages if msg.type == aiohttp.WSMsgType.TEXT: await ws.send_str('You said: {}'.format(msg.data)) elif msg.type == aiohttp.WSMsgType.ERROR: return ws return wsIn this example, we create a WebSocketResponse object and prepare the WebSocket connection using the prepare method. We then use the can_prepare method to check if the WebSocket connection is ready to receive messages. If the connection is not ready, we close the connection and return the WebSocketResponse object. Otherwise, we read incoming messages from the client using an async for loop and send a response back if the message type is TEXT. If an error occurs, we return the WebSocketResponse object. Package library: aiohttp.