Letters versus a phone call
HTTP is like writing letters. You only hear back when you write, so to follow a chat you'd have to keep writing "anything new?", and nearly every answer is "no".
A phone call works differently. Once the call is connected, the line stays open, and either of you can speak the moment you have something to say.
Why WebSockets exist
In HTTP the client always starts. Real-time features (chat, live scores, collaborative editing, multiplayer games, dashboards) can work around that with polling (ask every few seconds) or long polling (the server holds the request open until something happens). Both cost a full request with headers for each update, and polling adds delay.
A WebSocket is one persistent, full-duplex connection. Either side can send at any time, and each message costs only a few bytes of framing.
Starting the call
The call starts with an ordinary letter that has a note on the envelope: "can we switch to the phone?" If the other side agrees, it says so, and the same line turns into a call. When you're done, you both say goodbye and hang up.
The upgrade handshake
A WebSocket begins as an HTTP/1.1 request, so it works through the same ports, proxies and TLS as the rest of the site:
1GET /chat HTTP/1.12Upgrade: websocket3Connection: Upgrade4Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
The server answers 101 Switching Protocols with Sec-WebSocket-Accept, and from then on the TCP connection
carries frames: text, binary, ping, pong and close. Use wss:// (WebSocket over TLS) just as you'd use
https://. In the browser:
1const ws = new WebSocket("wss://shop.com/chat");2ws.onmessage = (e) => console.log(e.data);3ws.send("hi!");
A group call
A chat room is a switchboard with everyone's line plugged in. When one friend speaks, the switchboard repeats it to everyone else. It checks now and then that each line is still alive, and when one drops, that friend's phone calls back by itself.
Broadcasting and staying connected
The server keeps a set of open connections per room and fans out each message to the others. Ping/pong heartbeats keep idle connections alive through proxies and detect dead ones.
Connections will drop (phones change networks, servers redeploy), so clients reconnect with backoff and catch up on what they missed. With several server instances, a message arriving at one must reach clients connected to another, usually through a shared pub/sub channel such as Redis or Kafka.
When not to use it: for one-way updates (notifications, progress, live feeds), Server-Sent Events are simpler. They're plain HTTP, reconnect automatically, and work well with HTTP/2.
Security: browsers allow WebSocket connections to any origin, so servers must check the Origin header and
authenticate the connection themselves.