Real-time with WebSockets
Keep an open, two-way channel between server and client instead of polling for changes.
- explain the WebSocket upgrade handshake and how it differs from polling;
- build a bare-metal server with
wsand a batteries-included one with Socket.IO; - push updates, use rooms, and broadcast to many clients at once;
- keep connections alive with heartbeats and recover from drops with reconnection;
- reason about the real trade-offs: raw protocol vs framework, and scaling across processes.
1. From request/response to a live connection
You already know REST: the client sends a request, the server sends a response, done. To learn about new data the client must ask again. The oldest trick is polling -- hitting GET /messages every few seconds. It works but wastes requests when nothing changed and adds latency (a new message waits until the next poll). Long-polling improves this by holding the request open until data exists, but it is still one response per event and re-connects constantly.
A WebSocket solves the root problem. The client opens a normal HTTP request carrying an Upgrade: websocket header; the server agrees with a 101 Switching Protocols response; from that moment the same TCP connection is a bidirectional stream of frames. No new handshake per message, and the server can send whenever it wants.
Analogy. Polling is like phoning a shop every minute to ask "any news?". A WebSocket is leaving the line open: whenever there is news, either of you just speaks -- no redialing.