WebSocket: handshake, frames, ping/pong and closing
WebSocket (RFC 6455) turns an HTTP connection into a permanent two-way channel after a handshake with Upgrade and a 101 response. Messages travel as frames: text, binary and control (ping, pong, close). Code 1000 is a normal close, while 1006 is abnormal and never sent over the network. The protocol resends nothing, so the client reconnects with jitter and asks for missed events by id.
Networking · Real-time
After Wi-Fi comes back the chat shows new messages, but some went missing. Where did they go?
A user rides the metro: the network disappears for a minute and returns. The chat is online again, new messages arrive, but those that came during the drop never appeared. This is not a server bug: WebSocket does not deliver what was sent while the connection did not exist. The job of the client and the tester is to understand what the protocol guarantees and what the application must do. The lesson covers the handshake, frames, ping/pong and closing, and then proper reconnection.
How it works and why. HTTP is built as "request-response": the server sends nothing on its own. For chats, quotes and games this is inconvenient, so WebSocket (RFC 6455) turns one HTTP connection into a permanent two-way channel. The handshake is ordinary, and after it both sides can send messages at any moment without new requests and headers.
The life of a WebSocket connection
The handshake is an ordinary HTTP/1.1 request with Upgrade. The server answers with 101: "switching to another protocol". The Sec-WebSocket-Accept value is computed from the client's key so that a random HTTP service cannot pose as a WebSocket server. The address starts with ws:// or wss:// (WebSocket over TLS; in production only wss).
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://example.com
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Authentication happens right here, at the handshake. The browser WebSocket API does not allow custom headers (for example Authorization), so people use a cookie, a short-lived one-time ticket in the URL (an ordinary token in the query lands in logs and history) or a first message carrying the token. Origin is checked by the server: without it any foreign page opens a connection on behalf of the logged-in user (cross-site WebSocket hijacking).
Frames. A message consists of one or more frames: text (UTF-8), binary and control (ping, pong, close). Frames from the client are masked. Ping/pong checks that the connection is alive and keeps a proxy from closing it on idle timeout: usually the server sends ping and the browser answers pong automatically. Many applications add their own heartbeat messages, because ping/pong frames cannot be seen or sent from JS.
Closing is an exchange of close frames with a code that is worth being able to read:
| Code | Meaning |
|---|---|
1000 | normal closure |
1001 | going away: the page was closed or the server is restarting |
1008 | policy violation (for example, no rights): retrying is pointless |
1009 | message too big |
1011 | internal server error |
1006 | abnormal closure: there was no close frame. It is never sent over the wire, the client sees it only locally |
Client reconnection
An instant retry in a loop
After a server crash thousands of clients reconnect at once and knock it down again. Missed events never come back.
Backoff, jitter, resume
The delay grows and is randomly spread, there is an attempt limit, and after connecting the client asks for everything it missed by the last id.
Example: from lost messages to recovery. A client without recovery logic simply opens a new connection and listens on: everything that happened between the drop and the new connection is gone, and events in both directions are not repeated without acknowledgement. A working scheme has three parts: a delay with jitter (so thousands of clients do not knock at once), a different reaction to codes (do not retry 1008) and a request for what was missed by the id of the last message received:
let lastId = 0;
function connect(attempt = 0) {
const ws = new WebSocket('wss://example.com/ws');
ws.onopen = () => {
attempt = 0;
// ask for what was missed
ws.send(JSON.stringify({ type: 'resume', after: lastId }));
};
ws.onmessage = (e) => {
const msg = JSON.parse(e.data);
lastId = msg.id;
render(msg);
};
ws.onclose = (e) => {
// 1008 or 10 failed attempts in a row: stop retrying
if (e.code === 1008 || attempt >= 10) return;
const cap = Math.min(30_000, 500 * 2 ** attempt);
// jitter: a random delay from 0 to cap
setTimeout(() => connect(attempt + 1), Math.random() * cap);
};
}
Responsibility is shared here. The server must keep recent events or be able to give them by id; the client must remember where it stopped reading. Without the first, recovery is impossible; without the second, it duplicates messages. That is why messages have stable ids and handling is idempotent: a repeat of the same event does not put two messages on screen.
Limits and alternatives. WebSocket has no built-in redelivery, acknowledgement or ordering across connections. A balancer needs sticky connections or a shared subscription store, and proxies and firewalls sometimes cut WebSocket or close it on idle (see the lesson on proxies). If data flows only from the server, SSE is simpler (the next lesson). For WebSocket over HTTP/2 and HTTP/3 there are separate extensions (RFC 8441, RFC 9220), but most applications stay on the HTTP/1.1 handshake.
Common mistakes.
- Assuming that messages during a drop "arrive on their own": without catching up they are lost.
- Reconnecting instantly in a loop with no delay and jitter: after a server failure a connection storm forms.
- Retrying after
1008or an authentication error: pointless, and it loads the server. - Passing a long-lived token in the URL: it lands in proxy logs and history.
- Not checking Origin on the server: it opens the way to cross-site hijacking.
- Reading
1006as "the server closed normally": it is exactly a drop with no close frame.
Check yourself
In a client onclose received code 1006. What does it mean and how does it differ from 1000 or 1001?
Answer
1006 means abnormal closure: there was no close frame, the connection dropped (network, a killed process, a proxy timeout). It is not sent over the wire, the client only sets it locally. 1000 and 1001 arrive in a close frame: normal closure and "going away" (the page is closing or the server is restarting). The reaction to 1006 is reconnecting with catching up.
Why can an Authorization token not be set from a browser WebSocket and what are the options?
Answer
The browser WebSocket API does not allow custom headers. Options: a cookie (Origin must be checked), a short-lived one-time ticket in the URL obtained through an ordinary HTTP request, or a token in the first message after connecting. A long-lived token in the query string is dangerous because it lands in logs.