Real-time Chat Application (WebSocket)
Abstract
WebSockets are how the modern web does real-time — a persistent, two-way connection that lets a server push messages to clients the instant they arrive, with none of the polling overhead of plain HTTP. This project builds a WebSocket chat server in pure asyncioasyncio: clients connect, and every message is broadcast to all of them, live. It’s your introduction to asynchronous Python — asyncasync/awaitawait, coroutines, and an event loop handling many connections on a single thread. You’ll also fix a real deprecation in the starter code and add usernames, rooms, and a browser client.
You will leave understanding:
- What a WebSocket is and how it differs from request/response HTTP.
- How
asyncasync/awaitawaitlets one thread juggle thousands of connections. - The
async for message in websocketasync for message in websocketpattern for receiving. - Why the starter’s
asyncio.wait([...])asyncio.wait([...])broadcast is deprecated, and the modern replacement.
Prerequisites
- Python 3.7 or above (for
asyncio.runasyncio.run). - A text editor or IDE.
- The websockets library:
pip install websocketspip install websockets. - Basic understanding of functions; async is explained here.
- Helpful: the thread-based Basic Chatroom App for contrast.
Getting Started
Create the project
- Create a folder named
ws-chatws-chat. - Inside it, create
real_time_chat_application.pyreal_time_chat_application.py. - Install the dependency:
pip install websocketspip install websockets.
Write the code
real_time_chat_application.py
Source"""
Real-time Chat Application (WebSocket)
A Python application that enables real-time communication between clients using WebSocket.
Features include:
- Real-time messaging between multiple clients.
- Server-side implementation using `websockets` library.
- Client-side implementation for sending and receiving messages.
"""
import asyncio
import websockets
connected_clients = set()
async def handle_client(websocket, path):
"""Handle incoming messages from clients and broadcast them."""
connected_clients.add(websocket)
try:
async for message in websocket:
print(f"Received message: {message}")
await broadcast(message)
except websockets.ConnectionClosed:
print("Client disconnected")
finally:
connected_clients.remove(websocket)
async def broadcast(message):
"""Send a message to all connected clients."""
if connected_clients: # Ensure there are clients to broadcast to
await asyncio.wait([client.send(message) for client in connected_clients])
async def main():
"""Start the WebSocket server."""
server = await websockets.serve(handle_client, "localhost", 8765)
print("Server started on ws://localhost:8765")
await server.wait_closed()
if __name__ == "__main__":
asyncio.run(main())
"""
Real-time Chat Application (WebSocket)
A Python application that enables real-time communication between clients using WebSocket.
Features include:
- Real-time messaging between multiple clients.
- Server-side implementation using `websockets` library.
- Client-side implementation for sending and receiving messages.
"""
import asyncio
import websockets
connected_clients = set()
async def handle_client(websocket, path):
"""Handle incoming messages from clients and broadcast them."""
connected_clients.add(websocket)
try:
async for message in websocket:
print(f"Received message: {message}")
await broadcast(message)
except websockets.ConnectionClosed:
print("Client disconnected")
finally:
connected_clients.remove(websocket)
async def broadcast(message):
"""Send a message to all connected clients."""
if connected_clients: # Ensure there are clients to broadcast to
await asyncio.wait([client.send(message) for client in connected_clients])
async def main():
"""Start the WebSocket server."""
server = await websockets.serve(handle_client, "localhost", 8765)
print("Server started on ws://localhost:8765")
await server.wait_closed()
if __name__ == "__main__":
asyncio.run(main())
Run it
C:\Users\Your Name\ws-chat> python real_time_chat_application.py
Server started on ws://localhost:8765
# Connect with a browser console or a small client (see below).C:\Users\Your Name\ws-chat> python real_time_chat_application.py
Server started on ws://localhost:8765
# Connect with a browser console or a small client (see below).Step-by-Step Explanation
1. Tracking connected clients
connected_clients = set()connected_clients = set()A setset of active WebSocket connections. Sets make add/remove O(1) and prevent duplicates — perfect for a connection registry.
2. Handling a client (a coroutine)
async def handle_client(websocket, path):
connected_clients.add(websocket)
try:
async for message in websocket:
print(f"Received message: {message}")
await broadcast(message)
except websockets.ConnectionClosed:
print("Client disconnected")
finally:
connected_clients.remove(websocket)async def handle_client(websocket, path):
connected_clients.add(websocket)
try:
async for message in websocket:
print(f"Received message: {message}")
await broadcast(message)
except websockets.ConnectionClosed:
print("Client disconnected")
finally:
connected_clients.remove(websocket)async defasync def makes this a coroutine — a function that can pause at awaitawait and let other connections run. async for message in websocketasync for message in websocket yields each incoming message as it arrives, without blocking the other clients. The finallyfinally guarantees the client is removed from the registry even if it disconnects abruptly — critical for not broadcasting to dead sockets.
3. Broadcasting
async def broadcast(message):
if connected_clients:
await asyncio.wait([client.send(message) for client in connected_clients])async def broadcast(message):
if connected_clients:
await asyncio.wait([client.send(message) for client in connected_clients])Send the message to everyone. Heads-up: this line is deprecated in modern websocketswebsockets/asyncioasyncio — see the fix below.
4. Starting the server
async def main():
server = await websockets.serve(handle_client, "localhost", 8765)
print("Server started on ws://localhost:8765")
await server.wait_closed()
asyncio.run(main())async def main():
server = await websockets.serve(handle_client, "localhost", 8765)
print("Server started on ws://localhost:8765")
await server.wait_closed()
asyncio.run(main())websockets.servewebsockets.serve binds the port and runs handle_clienthandle_client for each connection. asyncio.run(main())asyncio.run(main()) creates the event loop, runs the coroutine, and cleans up — the standard async entry point.
Fix: Modernize the Broadcast
asyncio.wait([coro, ...])asyncio.wait([coro, ...]) with bare coroutines is deprecated (and broadcasting to a client that just disconnected raises). The clean, current approach:
async def broadcast(message):
if not connected_clients:
return
# gather runs all sends concurrently; return_exceptions keeps one
# failed send from cancelling the rest
await asyncio.gather(
*(client.send(message) for client in connected_clients),
return_exceptions=True,
)async def broadcast(message):
if not connected_clients:
return
# gather runs all sends concurrently; return_exceptions keeps one
# failed send from cancelling the rest
await asyncio.gather(
*(client.send(message) for client in connected_clients),
return_exceptions=True,
)Recent websocketswebsockets versions also offer a built-in websockets.broadcast(connected_clients, message)websockets.broadcast(connected_clients, message) helper that handles dead connections for you.
Add Usernames
Have each client send a name as its first message, then prefix broadcasts:
names = {} # websocket -> name
async def handle_client(websocket):
name = await websocket.recv() # first message is the name
names[websocket] = name
connected_clients.add(websocket)
await broadcast(f"*** {name} joined ***")
try:
async for msg in websocket:
await broadcast(f"{name}: {msg}")
finally:
connected_clients.discard(websocket)
await broadcast(f"*** {name} left ***")names = {} # websocket -> name
async def handle_client(websocket):
name = await websocket.recv() # first message is the name
names[websocket] = name
connected_clients.add(websocket)
await broadcast(f"*** {name} joined ***")
try:
async for msg in websocket:
await broadcast(f"{name}: {msg}")
finally:
connected_clients.discard(websocket)
await broadcast(f"*** {name} left ***")(Modern websocketswebsockets passes only websocketwebsocket to the handler — pathpath is no longer required.)
Add Rooms
Group clients into channels by keeping a dict[str, set]dict[str, set] of rooms and broadcasting only within the sender’s room — the same pattern Slack and Discord channels use.
A Browser Client
WebSockets are native to browsers — no library needed:
<script>
const ws = new WebSocket("ws://localhost:8765");
ws.onopen = () => ws.send("Alice"); // send username first
ws.onmessage = (e) => console.log(e.data); // print incoming
function send(text) { ws.send(text); }
</script><script>
const ws = new WebSocket("ws://localhost:8765");
ws.onopen = () => ws.send("Alice"); // send username first
ws.onmessage = (e) => console.log(e.data); // print incoming
function send(text) { ws.send(text); }
</script>WebSockets vs. Threads (vs. HTTP)
| Approach | Model | Scales to many clients? |
|---|---|---|
| HTTP polling | Repeated request/response | Poorly — wasteful, laggy |
| Thread per client | One OS thread each | Hundreds (threads are heavy) |
| asyncio + WebSocket | One loop, many coroutines | Thousands (cheap to suspend) |
This is why async exists: I/O-bound work (waiting on the network) suspends cheaply, so one thread serves enormous numbers of idle-but-connected clients.
Common Mistakes
| Problem | Cause | Fix |
|---|---|---|
DeprecationWarningDeprecationWarning on broadcast | asyncio.waitasyncio.wait with coroutines | Use asyncio.gather(..., return_exceptions=True)asyncio.gather(..., return_exceptions=True) |
| Server crashes when one client drops | sendsend to a closed socket | return_exceptions=Truereturn_exceptions=True, or websockets.broadcastwebsockets.broadcast |
handler() takes 1 arghandler() takes 1 arg error | Newer websocketswebsockets drops pathpath | Define handle_client(websocket)handle_client(websocket) |
| Messages never arrive | Mixed ws://ws:// and wss://wss://, or wrong port | Match scheme/port; wsswss needs TLS |
| Dead clients still in the set | Removed only on clean close | Remove in a finallyfinally block |
| Blocking call freezes everyone | Using sync I/O in a coroutine | Use async equivalents; never time.sleeptime.sleep |
Variations to Try
- Modern broadcast — the
gathergather/websockets.broadcastwebsockets.broadcastfix (do this first). - Usernames & system messages — join/leave notices.
- Chat rooms — multiple channels.
- Browser UI — an HTML/JS front end (above).
- Message history — replay the last N messages on join.
- Typing indicators / presence — show who’s online and typing.
- Authentication — validate a token on connect.
- Persistence — log messages to a database.
Real-World Applications
- Live chat & messaging — Slack, Discord, support widgets.
- Collaborative apps — Google Docs-style live editing.
- Live dashboards — real-time metrics, prices, scores.
- Multiplayer games — low-latency state updates.
Educational Value
- Async Python —
asyncasync/awaitawait, coroutines, the event loop. - WebSockets — persistent, bidirectional connections.
- Concurrency models — async vs. threads vs. polling.
- Keeping up with APIs — recognizing and fixing deprecations.
Next Steps
- Replace the deprecated broadcast with
asyncio.gatherasyncio.gather. - Add usernames, system messages, and rooms.
- Build a browser client and add message history.
- Add authentication and persistence.
Conclusion
You built a real-time chat server with asyncioasyncio and WebSockets, learned how one thread serves thousands of connections by suspending at awaitawait, and modernized a deprecated broadcast in the process. Persistent, push-based connections are the backbone of every live app you use — and async is how Python scales them. Full source on GitHub. Explore more networking projects on Python Central Hub.
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
