Appearance
WebSockets
A protocol that provides persistent, full-duplex communication between client and server over a single TCP connection.
- Normal HTTP — client always initiates, server can't push.
- WebSocket — both sides can send anytime.
HTTP vs WebSocket
HTTP (request-response):
Client --- request ---> Server
Client <-- response --- Server
(connection closes)WebSocket (persistent):
Client <===> Server (both send anytime, connection stays open)WebSocket Handshake
Starts as HTTP, then upgrades:
Client --- HTTP GET /chat
Upgrade: websocket
Connection: Upgrade
Server --- 101 Switching Protocols
Upgrade: websocket
Now it's a WebSocket connection ✓Uses HTTP only for the initial handshake — after that it's raw TCP frames.
Full Duplex vs Half Duplex
| Direction | Example |
|---|---|
| Simplex | One way only — TV broadcast |
| Half Duplex | Both ways, not simultaneously — walkie talkie |
| Full Duplex | Both ways simultaneously — phone call, WebSocket |
WebSocket vs Alternatives
| WebSocket | HTTP Polling | SSE | |
|---|---|---|---|
| Direction | Full duplex | Client only | Server → Client only |
| Connection | Persistent | New each time | Persistent |
| Overhead | Low | High | Low |
| Use case | Chat, gaming | Simple updates | Live feed, notifications |
- HTTP Polling — client asks server every X seconds "anything new?" — wasteful.
- SSE (Server Sent Events) — server pushes to client only, simpler than WS, good for notifications/feeds.
Use Cases
- Real-time chat (WhatsApp Web)
- Multiplayer games
- Collaborative editing (Google Docs)
- Live stock/crypto prices
- Live sports scores
Key Concepts
Heartbeat / Ping-Pong
- Both sides send periodic pings to keep connection alive.
- If no response → connection is dead, reconnect.
Reconnection
- Network drops → client must reconnect manually.
- Libraries like
socket.iohandle this automatically.
Scaling WebSockets
- Problem — connections are stateful, sticky to one server.
- Solution — Redis Pub/Sub to broadcast messages across multiple servers.
Server 1 (user A connected)
Server 2 (user B connected)
A sends message → Server 1 → Redis → Server 2 → Bsocket.io vs Raw WebSocket
- socket.io — fallback to polling if WS not supported, rooms, reconnection built in.
- Raw WebSocket — lighter, standard, no extra features.