WebSockets
HTTP asks. WebSockets scream continuously.
▶ the lesson · narrated sketch video · tap for sound
the intro
WebSockets open a persistent two-way connection between browser and server. Instead of asking for updates, both sides push messages the moment they happen — that is how chat, live scores, and collaborative apps feel instant.
fun fact ✦
Before WebSockets (2011), apps faked real-time with endless polling or “long polling” hacks.
the docs
the deep dive
the ideas behind the video — concepts, diagrams, a walkthrough and the traps to avoid
HTTP is a stack of letters: ask, receive, ask again, and the server cannot say a word until asked. A WebSocket is a phone call. It even begins as an ordinary HTTP request that asks to stop being one, the server agrees, and the same wire becomes a two-way line both sides can shout into at any moment.
from letters to a phone call
key terms
full duplex
Both sides talk at the same time over one connection, with no new requests.
server pushes firstupgrade
The opening handshake: a normal HTTP request asking to become a WebSocket. 101 means yes.
HTTP 101 Switchingroom
A server-side group of sockets. One emit reaches everyone in the room and no one else.
io.to("lobby")heartbeat
A tiny ping every 30 seconds or so, so idle routers and proxies do not kill the line.
ping → ponghow it works
- 1Ask to upgrade
The browser sends ws:// or wss:// with an Upgrade header. Still HTTP at this point.
- 2Server agrees
It replies 101 Switching Protocols, and the socket stops being request-response.
- 3Both sides push
Either party sends JSON events whenever something happens: a message, a score, a cursor.
- 4Ping to stay alive
A heartbeat every 30 seconds keeps sleepy routers from closing an idle connection.
the code, explained
a chat room in seven lines of Socket.IO
side by side
polling
- ask every N seconds
- trivially simple to build
- wasted requests when idle
- updates arrive late
websockets
- instant push, both directions
- one connection, no spam
- stateful and harder to scale
- needs heartbeats to survive
Connections live in one server's memory. Put user A on server 1 and user B on server 2, and their chat room silently splits in half: no error, just ghosts. Two or more instances need a shared bus like Redis pub/sub to relay messages.
quick answers
Do WebSockets work over HTTPS?
Yes, wss:// is the TLS version, and production almost always requires it. Plain ws:// gets blocked by many corporate networks and some proxies.
Can I just use fetch and setTimeout?
For occasional one-way updates, yes, or Server-Sent Events, which are simpler. For two-way low-latency traffic like chat, use a WebSocket.
Socket.IO or the raw ws library?
Raw ws is lighter and standards-based. Socket.IO adds rooms, auto-reconnect, and fallbacks. Pick per project; the concepts are identical.
quick hits about WebSockets
short answers · interviews, tips, trivia & hidden gems