WebSockets
HTTP is a one-shot request and reply. WebSockets keep the line open so the server can talk back whenever it wants.
Normal HTTP is a monologue with a reply: you ask, the server answers, the connection is done. That is fine for loading a page, but awful for a chat app or a live scoreboard, where the server needs to push updates to you. WebSockets solve exactly that.
The upgrade
A WebSocket starts life as an ordinary HTTP request with a special header asking to switch protocols:
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
If the server agrees, it replies 101 Switching Protocols, and from that point the same TCP connection is a full-duplex WebSocket — both sides can send frames at any time, with almost no per-message overhead.
Using one in the browser
const ws = new WebSocket("wss://example.com/chat");
ws.onopen = () => ws.send("hello");
ws.onmessage = (e) => console.log("got:", e.data);
ws.onclose = () => console.log("closed");
Note the wss:// scheme — that is WebSocket over TLS, the encrypted version, just like https is to http.
When to reach for them
- Chat and messaging.
- Live dashboards, prices, sports scores.
- Multiplayer games and collaborative editors.
- Anything where waiting for the client to ask again would feel laggy.
Alternatives
If you only need the server to push to the client (not both ways), Server-Sent Events are simpler and run over plain HTTP. For request/response with occasional pushes, long-polling still works. WebSockets win when traffic is genuinely two-way and frequent.