Skip to content

Real-time with WebSockets

Beginning of the lesson

Real-time with WebSockets

Keep an open, two-way channel between server and client instead of polling for changes.

Big idea: Plain HTTP is request/response: the client asks, the server answers, the connection closes. That model cannot let the server speak first. A WebSocket upgrades one HTTP connection into a persistent, full-duplex pipe that stays open, so either side can push a message the instant it has something to say -- the foundation of chat, live dashboards, multiplayer games, and collaborative editors.
By the end you will be able to:
  • explain the WebSocket upgrade handshake and how it differs from polling;
  • build a bare-metal server with ws and 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.

HTTP polling Client Server GET /messages (empty) repeat forever WebSocket Client Server Upgrade: websocket 101 Switching frames, both ways
Polling reopens a request per check; a WebSocket handshakes once, then frames flow in both directions on one open connection.

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.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers