Home › Networking › WebSockets
Networking
WebSockets
A normal HTTP request is one-and-done: ask, get an answer, close. WebSockets keep a connection open so the server and the page can send messages whenever they want.
Why they exist
For anything live, chat, game state, a stock ticker, polling the server over and over is wasteful and slow. A WebSocket stays open so either side can push a message the instant it has one.
The upgrade
It starts as a normal HTTP request with an Upgrade: websocket header. If the server agrees, the same TCP connection switches to the WebSocket protocol and stays open.
const ws = new WebSocket('wss://example.com/socket');
ws.onmessage = (e) => console.log('got', e.data);
ws.onopen = () => ws.send('hello');
Messages
After the upgrade, both sides send discrete messages (text or binary) in small framed chunks. No status codes, no headers per message, just data.