The user wants a Python program simulating a chat server using WebSockets.
-
Identify the key components:
- Server: Needs to handle multiple connections, broadcast messages to all connected clients, and manage disconnections.
- Client: Needs to connect to the server, send messages, and receive/display messages from others. To make it a complete demonstration, I should probably provide code for both the server and the client.
- Library:
websockets is the standard, modern Python library for this. asyncio is required since websockets is built on it.
-
Server Design:
- State: Needs a set to keep track of active connections (e.g.,
connected_clients).
- Handler Function: An
async function that takes websocket and path (though path is deprecated in newer versions, I should check the signature. Actually, modern websockets just takes websocket).
- Logic:
- Register client (add to set).
- Loop forever:
- Wait for a message.
- If message received, broadcast it to everyone else (or everyone including sender).
- Handle disconnection (try/finally block to remove client from set).
- Broadcasting: Iterate through
connected_clients and send the message. Need to handle potential errors if a client disconnects while broadcasting.
-
Client Design:
- Input: Needs to read input from the user (console).
- Output: Needs to print incoming messages.
- Concurrency: Since reading input (
input()) blocks the thread, but we also need to listen for incoming messages, I need two concurrent tasks.
- Task 1: Listen for user input and send to server.
- Task 2: Listen for messages from server and print to console.
- Library:
websockets.connect.
-
Refining the Code Structure:
-
Prerequisites: Mention pip install websockets.
-
Server Code:
import asyncio
import websockets
connected = set()
async def handler(websocket):
connected.add(websocket)
try:
async for message in websocket:
# Broadcast
for conn in connected:
if conn != websocket: # Optional: usually chat includes sender, but logic varies. Let's include sender for a better UX.
await conn.send(message)
finally:
connected.remove(websocket)
# ... start_server boilerplate ...
Correction: If I exclude the sender, the sender doesn't see what they typed unless the client prints it locally. Standard chat servers often echo back so the client knows it was sent. Let's broadcast to everyone in the set for simplicity, so the sender sees their own message appear as "received".
-
Client Code:
import asyncio
import websockets
async def receive_messages(websocket):
async for message in websocket:
print(message)
async def main():
async with websockets.connect("ws://localhost:8765") as ws:
# Need to run input loop and receive loop concurrently
await asyncio.gather(receive_messages(ws), send_messages(ws))
Problem with input(): input() is a blocking IO call. It doesn't play nice with asyncio by default.
Solution: Run the input loop in a separate thread using loop.run_in_executor or just keep it simple. Since this is a simulation/demo, blocking the input is fine if the receiving is handled asynchronously. However, input() blocks the main thread, preventing the asyncio event loop from processing incoming messages if they share the same thread context in a naive implementation.
Better Approach:
Task 1: Input loop (needs to offload input() to a thread or use a library like aioconsole).
Task 2: Receiver loop.
Simplest approach for a tutorial: Use aioconsole if possible, but that requires an extra install.
Alternative standard approach: Use asyncio's run_in_executor for the input. Or, create a thread for receiving and keep input in the main thread (but websockets requires the loop).
Let's go with the standard websockets pattern:
Two tasks running in asyncio.gather.
listen() (async for message)
send() (infinite loop with input()).
Wait, input() blocks the whole interpreter thread. This means listen() won't get CPU time until input() returns.
Fix: The client code is tricky in standard Python without extra libraries.
Approach A: Use threading for the receiver.
Approach B: Use loop.run_in_executor(None, input) to make input non-blocking relative to the event loop.
Let's write the Client using run_in_executor:
async def send(websocket):
loop = asyncio.get_event_loop()
while True:
message = await loop.run_in_executor(None, input, "> ")
await websocket.send(message)
async def recv(websocket):
async for message in websocket:
print(f"< {message}")
-
Polishing:
- Add comments explaining the code.
- Add error handling (simple try/except).
- Make sure the port matches.
- Format the output clearly.
-
Drafting the response:
- Start with installation instructions.
- Provide
server.py.
- Provide
client.py.
- Explain how to run them.
(Self-Correction during drafting): In the server broadcast loop, I should catch websockets.exceptions.ConnectionClosed inside the loop in case a client drops while iterating. Or, simpler, just try/except around the send.
Let's refine the Server Broadcast:
for conn in connected:
try:
await conn.send(message)
except websockets.exceptions.ConnectionClosed:
# Handle specific error or just pass
pass
Actually, the finally block in the handler handles removal, but if an error occurs during send, it might break the loop. Using websockets.broadcast (available in newer versions) is cleaner.
websockets.broadcast(connected, message) is a helper added in recent versions. I should check if it's standard enough. Yes, it is very useful. I will use that if I assume a reasonably recent version, but a manual loop is safer for generic compatibility. Let's stick to the manual loop for clarity on how it works, or use the helper and mention it. Let's use the helper websockets.broadcast as it's the idiomatic way now.
-
Final Code Structure Plan:
- Server:
connected set.
async def handler(websocket):
- Register.
async for message in websocket:
websockets.broadcast(connected, message)
- Unregister (finally).
start_server = websockets.serve(handler, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(...)
- Client:
- Connect.
asyncio.gather(producer_handler, consumer_handler).
producer_handler handles input (using run_in_executor).
consumer_handler handles printing messages.
-
Writing the actual response. (Proceeding to generate output based on these steps).
To run this simulation, you will need the websockets library. You can install it using pip:
pip install websockets
Here is the complete solution. It consists of two separate files: one for the Server and one for the Client.
1. The Server Code (server.py)
This script handles multiple connections and broadcasts messages from one user to all others.
import asyncio
import websockets
# Set to keep track of active connections
connected_clients = set()
async def broadcast_message(message, sender_ws):
"""Sends a message to all connected clients except the sender."""
if not connected_clients:
return
# Create a list of tasks to send messages concurrently
# We use websockets.broadcast if available (library version >= 10.0),
# otherwise we iterate manually. Here is the manual iteration for clarity:
for client in connected_clients:
if client != sender_ws:
try:
await client.send(message)
except websockets.exceptions.ConnectionClosed:
# Client disconnected unexpectedly; handled in the main loop
pass
async def handler(websocket):
"""Handles a single client connection."""
# Register new client
connected_clients.add(websocket)
print(f"New client connected. Total clients: {len(connected_clients)}")
try:
# Notify everyone that a new user joined
await broadcast_message("A new user has joined the chat.", websocket)
# Listen for messages from this client
async for message in websocket:
print(f"Received: {message}")
# Broadcast the message to other clients
await broadcast_message(f"User: {message}", websocket)
except websockets.exceptions.ConnectionClosed:
print("Client disconnected abruptly.")
finally:
# Unregister client
connected_clients.remove(websocket)
print(f"Client left. Total clients: {len(connected_clients)}")
await broadcast_message("A user has left the chat.", websocket)
async def main():
print("Server started on ws://localhost:8765")
# Start the server
async with websockets.serve(handler, "localhost", 8765):
# Run forever
await asyncio.Future()
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("Server shutting down.")
2. The Client Code (client.py)
This script connects to the server. It needs to do two things at once: listen for incoming messages (to print them) and wait for user input (to send them). We use asyncio to handle these tasks concurrently.
import asyncio
import websockets
async def receive_messages(websocket):
"""Task 1: Continuously listen for messages from the server."""
try:
async for message in websocket:
print(f"\n{message}")
print("> ", end="", flush=True) # Re-print input prompt
except websockets.exceptions.ConnectionClosed:
print("\nDisconnected from server.")
async def send_messages(websocket):
"""Task 2: Wait for user input and send to server."""
# Small delay to ensure connection is established before prompting
await asyncio.sleep(0.1)
print("Connected to chat! Type 'exit' to quit.")
while True:
# We use asyncio.to_thread to run the blocking input() function
# without freezing the event loop that listens for incoming messages.
message = await asyncio.to_thread(input, "> ")
if message.lower() == "exit":
await websocket.close()
break
await websocket.send(message)
async def main():
uri = "ws://localhost:8765"
try:
async with websockets.connect(uri) as websocket:
# Create two concurrent tasks: receiving and sending
receive_task = asyncio.create_task(receive_messages(websocket))
send_task = asyncio.create_task(send_messages(websocket))
# Wait for both tasks to finish (usually when user types 'exit')
done, pending = await asyncio.wait(
[receive_task, send_task],
return_when=asyncio.FIRST_COMPLETED,
)
# Cancel any pending tasks if one finishes
for task in pending:
task.cancel()
except ConnectionRefusedError:
print("Could not connect to the server. Is it running?")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\nClient closed.")
How to Run the Simulation
-
Open a terminal (Command Prompt or Terminal) and run the server:
python server.py
You will see: Server started on ws://localhost:8765
-
Open a second terminal (or a new tab) and run the first client:
python client.py
-
Open a third terminal and run a second client to simulate multiple users:
python client.py
Now, type a message in one of the client terminals. It will appear in the other client's terminal instantly.