Write a Python program to simulate a chat server using websockets.
- User
Write a Python program to simulate a chat server using websockets.
- Assistant
Reviewing websocket changes
I need to be cautious because the websockets library API changed between versions 10.x and 12.x. The typical pattern now includes defining a handler for connections where messages are relayed among users.
The websockets.serve function should be used in an async context, and I should ensure to manage closed websockets effectively. While it's good to keep the code minimal, incorporating comments for clarity is essential. I also need to highlight concurrency issues and mention the difference between broadcasting methods that include the sender.Preparing chat server code
I’m thinking about adding simple text-based logs for user messages. The user requested a Python program to simulate a chat server using websockets without extra constraints, which means I can keep it straightforward.
I plan to include a short description, installation instructions, the server code, and possibly a simple client for testing. I’ll focus on broadcasting messages to all clients while handling join and leave events. I also need to ensure I'm careful about the handler signature, as it changed in version 12.Clarifying websockets handler
I'm reviewing the websockets 12.0 documentation, which shows the handler signature as just
websocket. I need to remember that the default is nowws_handler(websocket)without a path parameter, which is a change from earlier versions that included it.To stay safe and compatible with modern libraries, I can define my handler as
def handler(websocket)without includingpath, as it was removed in version 10. However, I see many examples still use the two-argument format, so I'll opt for the simpler version.Implementing websocket serverIn version 10, the websockets library changed to a new connection handler signature, so now it primarily uses
ws_handler(websocket). I'm planning to keep things modern and straightforward, but I also need to manage connections.I'll set up a basic handler that adds each websocket to a
connectedset and broadcasts incoming messages to other clients. If any broadcasts raise exceptions due to closed websockets, I’ll just ignore those errors for simplicity. For brevity, I can use the built-inwebsockets.broadcastfunction to handle sending messages, including the sender if needed.Finalizing chat server implementationThe chat server is shaping up nicely, and I'll have the asynchronous handler manage connected clients. Each client will be welcomed, and the server will broadcast messages while ensuring that messages aren't sent back to the sender unless that's desired for the chat experience.
Since the user didn't ask for a client, I think I'll focus on the server instead, but I can mention testing with tools like
websocat. I'll ensure to include details about installing thewebsocketslibrary and provide clear, commented code for the server so users can easily follow along! Below is a minimal but complete example of a WebSocket-based chat server in Python that broadcasts messages to all connected clients.It uses the third‑party
websocketslibrary.
1. Install dependency
pip install websocketsRequires Python 3.8+.
2. Chat server (
chat_server.py)import asyncio import websockets # Keep track of connected clients connected_clients = set() async def handle_client(websocket): """ Handle a single client connection: receive messages and broadcast them. """ # Register new client connected_clients.add(websocket) client_id = id(websocket) print(f"Client {client_id} connected. Total clients: {len(connected_clients)}") try: # Optional: send a welcome message await websocket.send("Welcome to the chat server!") # Receive messages from this client async for message in websocket: print(f"Received from {client_id}: {message}") # Prefix message with a simple client identifier broadcast_message = f"[{client_id}] {message}" # Broadcast to all *other* connected clients tasks = [ client.send(broadcast_message) for client in connected_clients if client is not websocket ] if tasks: # Only await if there is at least one recipient await asyncio.gather(*tasks, return_exceptions=True) except websockets.ConnectionClosedOK: pass except websockets.ConnectionClosedError: pass finally: # Unregister client connected_clients.remove(websocket) print(f"Client {client_id} disconnected. Total clients: {len(connected_clients)}") async def main(): # Start the WebSocket server async with websockets.serve(handle_client, "0.0.0.0", 8765): print("Chat server started on ws://0.0.0.0:8765") # Run forever await asyncio.Future() if __name__ == "__main__": asyncio.run(main())
3. How to test
Run the server:
python chat_server.pyThen connect with any WebSocket client, for example:
-
Browser console:
const ws = new WebSocket("ws://localhost:8765"); ws.onmessage = (ev) => console.log("Received:", ev.data); ws.onopen = () => ws.send("Hello from the browser!"); -
Or use multiple terminals with a CLI WebSocket client like
websocat, or write a small Python client usingwebsockets.connect.
Any message sent by one client will be broadcast to all the others.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.