3 Hours

17. Real-Time Communication with WebSockets

Real-Time

WebSockets enable full-duplex, real-time communication between clients and servers. Unlike HTTP, where the client must request data, WebSockets allow the server to push data to clients instantly. This is essential for chat applications, live notifications, gaming, and real-time dashboards. To test these examples, save to main.py and run uvicorn main:app --reload.

Basic WebSocket Endpoint

FastAPI provides built-in support for WebSockets using the WebSocket class.

Python 3
from fastapi import FastAPI, WebSocket, WebSocketDisconnect

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    try:
        while True:
            data = await websocket.receive_text()
            await websocket.send_text(f"Server received: {data}")
    except WebSocketDisconnect:
        print("Client disconnected")
Local Testing: Use a WebSocket client like wscat: wscat -c ws://localhost:8000/ws. Send messages and see them echoed back.

WebSocket Connection Manager

A connection manager tracks active WebSocket connections and enables broadcasting messages to all clients.

Python 3
from typing import List
from fastapi import FastAPI, WebSocket, WebSocketDisconnect

class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def send_personal_message(self, message: str, websocket: WebSocket):
        await websocket.send_text(message)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)

manager = ConnectionManager()

@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: str):
    await manager.connect(websocket)
    await manager.broadcast(f"Client {client_id} joined the chat")

    try:
        while True:
            data = await websocket.receive_text()
            await manager.broadcast(f"Client {client_id} says: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
        await manager.broadcast(f"Client {client_id} left the chat")

Authentication for WebSockets

Secure WebSocket connections by validating tokens during the handshake.

Python 3
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Query, HTTPException
import jwt

SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"

app = FastAPI()

@app.websocket("/ws/secure")
async def websocket_secure(websocket: WebSocket, token: str = Query(...)):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        user_id = payload.get("sub")
        if not user_id:
            await websocket.close(code=1008, reason="Invalid token")
            return
    except jwt.InvalidTokenError:
        await websocket.close(code=1008, reason="Invalid token")
        return

    await websocket.accept()
    await websocket.send_text(f"Welcome user {user_id}")

    try:
        while True:
            data = await websocket.receive_text()
            await websocket.send_text(f"Echo: {data}")
    except WebSocketDisconnect:
        print(f"User {user_id} disconnected")

WebSocket with Rooms (Group Chat)

Create rooms so clients can communicate within specific groups.

Python 3
from typing import Dict, Set

class RoomManager:
    def __init__(self):
        self.rooms: Dict[str, Set[WebSocket]] = {}

    async def join_room(self, room: str, websocket: WebSocket):
        if room not in self.rooms:
            self.rooms[room] = set()
        self.rooms[room].add(websocket)

    def leave_room(self, room: str, websocket: WebSocket):
        if room in self.rooms:
            self.rooms[room].discard(websocket)

    async def broadcast_to_room(self, room: str, message: str, sender: WebSocket = None):
        if room in self.rooms:
            for connection in self.rooms[room]:
                if connection != sender:
                    await connection.send_text(message)

room_manager = RoomManager()

@app.websocket("/ws/chat/{room_id}")
async def chat_room(websocket: WebSocket, room_id: str):
    await websocket.accept()
    await room_manager.join_room(room_id, websocket)

    try:
        while True:
            data = await websocket.receive_text()
            await room_manager.broadcast_to_room(room_id, data, websocket)
    except WebSocketDisconnect:
        room_manager.leave_room(room_id, websocket)
        await room_manager.broadcast_to_room(room_id, f"User left the room")

Handling Different Message Types (JSON)

WebSockets can send JSON data for structured communication.

Python 3
import json
from pydantic import BaseModel

class ChatMessage(BaseModel):
    type: str
    content: str
    sender: str
    timestamp: float

@app.websocket("/ws/json")
async def websocket_json(websocket: WebSocket):
    await websocket.accept()

    try:
        while True:
            data = await websocket.receive_text()

            try:
                message = json.loads(data)
                validated = ChatMessage(**message)

                if validated.type == "message":
                    response = {"type": "message", "content": f"Echo: {validated.content}"}
                elif validated.type == "typing":
                    response = {"type": "typing", "sender": validated.sender}
                else:
                    response = {"type": "error", "content": "Unknown message type"}

                await websocket.send_json(response)
            except json.JSONDecodeError:
                await websocket.send_json({"type": "error", "content": "Invalid JSON"})
    except WebSocketDisconnect:
        pass

Knowledge Check

Ready to test your understanding of 17. Real-Time Communication with WebSockets?

Back