Skip to content

Real-time Chat Application (WebSocket)

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 asyncio: clients connect, and every message is broadcast to all of them, live. It’s your introduction to asynchronous Python — async/await, 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 async/await lets one thread juggle thousands of connections.
  • The async for message in websocket pattern for receiving.
  • Why the starter’s asyncio.wait([...]) broadcast is deprecated, and the modern replacement.
  • Python 3.7 or above (for asyncio.run).
  • A text editor or IDE.
  • The websockets library: pip install websockets.
  • Basic understanding of functions; async is explained here.
  • Helpful: the thread-based Basic Chatroom App for contrast.
  1. Create a folder named ws-chat.
  2. Inside it, create real_time_chat_application.py.
  3. Install the dependency: pip install websockets.
real_time_chat_application.py pch.viewSource
real_time_chat_application.py
"""
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())
command
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).

Read from the top: this is what runs when you execute the file, and which function calls which. It is generated from the code, so it cannot drift from it.

diagram Diagram mermaid
real_time_chat_application.py
connected_clients = set()

A set of active WebSocket connections. Sets make add/remove O(1) and prevent duplicates — perfect for a connection registry.

real_time_chat_application.py
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 makes this a coroutine — a function that can pause at await and let other connections run. async for message in websocket yields each incoming message as it arrives, without blocking the other clients. The finally guarantees the client is removed from the registry even if it disconnects abruptly — critical for not broadcasting to dead sockets.

real_time_chat_application.py
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 websockets/asyncio — see the fix below.

real_time_chat_application.py
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.serve binds the port and runs handle_client for each connection. asyncio.run(main()) creates the event loop, runs the coroutine, and cleans up — the standard async entry point.

asyncio.wait([coro, ...]) with bare coroutines is deprecated (and broadcasting to a client that just disconnected raises). The clean, current approach:

broadcast_fixed.py
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 websockets versions also offer a built-in websockets.broadcast(connected_clients, message) helper that handles dead connections for you.

Have each client send a name as its first message, then prefix broadcasts:

usernames.py
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 websockets passes only websocket to the handler — path is no longer required.)

Group clients into channels by keeping a dict[str, set] of rooms and broadcasting only within the sender’s room — the same pattern Slack and Discord channels use.

WebSockets are native to browsers — no library needed:

client.html
<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>
ApproachModelScales to many clients?
HTTP pollingRepeated request/responsePoorly — wasteful, laggy
Thread per clientOne OS thread eachHundreds (threads are heavy)
asyncio + WebSocketOne loop, many coroutinesThousands (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.

ProblemCauseFix
DeprecationWarning on broadcastasyncio.wait with coroutinesUse asyncio.gather(..., return_exceptions=True)
Server crashes when one client dropssend to a closed socketreturn_exceptions=True, or websockets.broadcast
handler() takes 1 arg errorNewer websockets drops pathDefine handle_client(websocket)
Messages never arriveMixed ws:// and wss://, or wrong portMatch scheme/port; wss needs TLS
Dead clients still in the setRemoved only on clean closeRemove in a finally block
Blocking call freezes everyoneUsing sync I/O in a coroutineUse async equivalents; never time.sleep
  1. Modern broadcast — the gather/websockets.broadcast fix (do this first).
  2. Usernames & system messages — join/leave notices.
  3. Chat rooms — multiple channels.
  4. Browser UI — an HTML/JS front end (above).
  5. Message history — replay the last N messages on join.
  6. Typing indicators / presence — show who’s online and typing.
  7. Authentication — validate a token on connect.
  8. Persistence — log messages to a database.
  • 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.
  • Async Pythonasync/await, coroutines, the event loop.
  • WebSockets — persistent, bidirectional connections.
  • Concurrency models — async vs. threads vs. polling.
  • Keeping up with APIs — recognizing and fixing deprecations.
  • Replace the deprecated broadcast with asyncio.gather.
  • Add usernames, system messages, and rooms.
  • Build a browser client and add message history.
  • Add authentication and persistence.

You built a real-time chat server with asyncio and WebSockets, learned how one thread serves thousands of connections by suspending at await, 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.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading