write a minimal websockets server in python
- User
write a minimal websockets server in python
Assistant
Sure, here's a minimal WebSocket server written in Python:
import asyncio import websockets class WebSocketServer: def __init__(self): self.clients = [] self.connection_pool = asyncio.Queue() async def handle_client(self, client): async with client: await client.send_json({"message": "Hello, WebSocket!"}) self.connection_pool.put_nowait(client) async def run(self): while True: try: with websockets.connect(self.connection_pool.get()) as websocket: await websocket.wait_for_open() self.clients.append(websocket) await websocket.send_json({"message": "Connected"}) except asyncio.CancelledError: break async def run_forever(self): while True: try: await self.run() except asyncio.CancelledError: break async def send_message(self, client, message): with websockets.connect(self.connection_pool.get()) as websocket: await websocket.send_json({"message": message}) self.send(client, "Received message: " + message) async def send_message_to_all(self, message): with websockets.connect(self.connection_pool.get()) as websocket: await websocket.send_json({"message": message}) self.send(websocket, "Received message: " + message) async def close_all_clients(self): await asyncio.gather(*(client.close() for client in self.clients)) async def on_close(self, ws): self.clients.remove(ws) await self.send_message_to_all(ws.message)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.