Web & APIs

WebSocket

/ WEB-sock-it /

A WebSocket is a way to keep a live, two-way line open between the browser and the server, so messages can flow both directions the instant they happen. It's what powers chat apps, live scores, multiplayer games, and 'someone is typing…' — anything where the server needs to push news to you without being asked first.

To see why it matters, picture the normal way the web works: request and response, like sending letters. The browser mails a question, the server mails an answer, and then the line goes dead until the browser writes again. The server can't speak up on its own. If you wanted live updates that way, you'd have to keep nagging — 'anything new? anything new?' — over and over, which is slow and wasteful.

A WebSocket replaces the letters with a phone call that stays connected. After one quick setup (a 'handshake' that upgrades an ordinary connection), the line stays open and either side can talk whenever it likes — no re-asking, no delay. That open channel is the whole point: it makes the server able to tap you on the shoulder the moment something changes.

const ws = new WebSocket("wss://chat.example.com");
ws.onmessage = (e) => console.log("server says:", e.data);
ws.send("hello!");  // and you can talk back, any time

One open connection: the server can push to you, and you can send back, whenever.

Plain HTTP is request-then-response; a WebSocket keeps the line open so the server can speak first.

Also called
wswssreal-time connection