WebSocket — real-time bidirectional
Persistent connection. Server can push to client without the client asking. Used for live updates, chat, notifications.
@app.websocket('/path') — registers a WebSocket endpoint. WebSocket is a PERSISTENT connection — unlike HTTP (request → response → close), WebSocket stays open and EITHER side can send at any time. await ws.accept() — must be called first to complete the handshake. await ws.receive_text() / receive_json() / receive_bytes() — block until a message arrives. await ws.send_text() / send_json() / send_bytes() — send to THIS client. WebSocketDisconnect exception — raised when the client closes the tab. ConnectionManager pattern: keep a list of active connections, broadcast to all of them. Use cases: live leaderboards, chat, notifications, real-time dashboards, multiplayer games. WebSocket vs polling: WS pushes instantly (0ms lag); polling checks every N seconds (N/2 lag average).
-
Change '/ws/chat' to '/ws/notifications'→ different endpoint URL -
Change send_text to send_json with {user: 'x', msg: data}→ structured messages -
Add a 'send_to_sender_only' method that sends only to the originating ws→ private message -
Add a rate limiter: refuse more than 5 messages per second from one client→ anti-spam