WebSocket umožňuje obousměrnou real-time komunikaci. Chat, live notifications, collaborative editing.
Server — FastAPI¶
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI() connections: list[WebSocket] = [] @app.websocket(“/ws”) async def websocket_endpoint(ws: WebSocket): await ws.accept() connections.append(ws) try: while True: data = await ws.receive_text() for conn in connections: await conn.send_text(f”User: {data}”) except WebSocketDisconnect: connections.remove(ws)
Klient — JavaScript¶
const ws = new WebSocket(‘ws://localhost:8000/ws’); ws.onopen = () => console.log(‘Connected’); ws.onmessage = (event) => { const msg = event.data; document.getElementById(‘messages’).innerHTML += `
${msg}
`; }; ws.onclose = () => setTimeout(() => location.reload(), 3000); document.getElementById(‘send’).onclick = () => { ws.send(document.getElementById(‘input’).value); };
Klíčový takeaway¶
WebSocket pro real-time bidirectional komunikaci. Reconnect logic na klientu. Server-Sent Events pro one-way.