Manuál
Kompletní průvodce WebSocket
WebSocket umožňuje obousměrnou real-time komunikaci mezi klientem a serverem.
HTTP vs WebSocket
- HTTP — request/response, stateless, polling
- WebSocket — persistent connection, bidirectional, real-time
Handshake
GET /ws HTTP/1.1
Upgrade: websocket
Connection: Upgrade
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Upgrade: websocket
Connection: Upgrade
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Server (Node.js)
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (ws) => {
ws.on("message", (data) => {
// broadcast to all
wss.clients.forEach((client) => client.send(data));
});
});
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (ws) => {
ws.on("message", (data) => {
// broadcast to all
wss.clients.forEach((client) => client.send(data));
});
});
Client
const ws = new WebSocket("ws://localhost:8080");
ws.onmessage = (event) => console.log(event.data);
ws.send("Hello");
ws.onmessage = (event) => console.log(event.data);
ws.send("Hello");
Use cases
- Chat aplikace
- Live notifications
- Real-time dashboardy
- Collaborative editing
- Gaming
- Trading/finance feeds
Scaling
WebSocket drží persistent connection. Pro scaling: Redis pub/sub pro koordinaci mezi servery. Nebo Socket.io s Redis adapter.
Alternativy
- SSE (Server-Sent Events) — jednosměrný (server → client), jednodušší
- Long polling — fallback pro starší klienty
- gRPC streaming — pro service-to-service
Kdy WebSocket
Real-time bidirectional data. Pro jednosměrný stream (notifications, feeds) zvažte SSE — jednodušší.