Ever played with a walkie-talkie? Only one person can talk at a time: press the button, talk, let go of the button, then take turns. Talking in turns like this is called half-duplex. On a phone, Mrs. Rini and Eko can talk at the same moment without waiting for their turn. This is called full-duplex. Plain HTTP is more like letters: one letter goes out, one reply comes back.
WebSocket works like that phone. Its rules are written in RFC 6455, the WebSocket standard. WebSocket turns one HTTP request into a connection that stays open. Over that connection, the browser and the server can send each other messages at any time.
Handshake: from HTTP to WebSocket
The connection starts as an ordinary HTTP request that asks to "switch protocols". Below is the handshake from Mrs. Rini's board to the realtime server, with the sample key from RFC 6455 (top: the browser's request, bottom: the server's answer):
GET /board HTTP/1.1
Host: localhost:3000
Connection: Upgrade
Upgrade: websocket
Origin: http://localhost:8000
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Upgrade: websocketandConnection: Upgrade: the browser asks for this connection's protocol to be switched to WebSocket.Sec-WebSocket-Key: a key of 16 random bytes, new for every connection, written in base64 (a way to write bytes as letters and digits), so it is 24 characters long.101 Switching Protocols: the server agrees. After the blank line that ends this answer's headers, the same TCP connection (the network connection HTTP travels on) no longer speaks HTTP.
Guess first: the browser sends Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==. What must the server put in Sec-WebSocket-Accept: the same key, a new random key, or a value computed from that key?
Sec-WebSocket-Accept is computed from the key, in three steps:
- Append the GUID, a fixed text from RFC 6455, to the key.
- Take the SHA-1 of the result, a 20-byte fingerprint of it.
- Turn those 20 bytes into base64 (28 characters).
In Node.js code:
import { createHash } from 'node:crypto'
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' // fixed, written in RFC 6455
const key = 'dGhlIHNhbXBsZSBub25jZQ=='
console.log(createHash('sha1').update(key + GUID).digest('base64')) // s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
So the answer is a value computed from that key. The browser computes the same thing. If the results differ, the connection fails. In a test with Chromium 147, the key /YWRojGG13C3Iy7Ca8KYuQ== was answered with g87MRT1zr43h8qMK5LukGdNvXxM= and accepted. The Accept is not a password: it only proves the server really understands WebSocket.
After the handshake the connection uses the WebSocket protocol, not HTTP any more. Its address starts with ws:// (port 80) or wss:// (port 443). wss:// runs over TLS, the encryption that https:// uses too. An https:// page must use wss://. For ws://, Chromium and Firefox throw a SecurityError, and Safari makes it fail with an error event.
Frame: the envelope around each message
Every message is sent in a frame, like a letter inside an envelope. The message itself is called the payload, and the frame's header is small. FIN and MASK are only 1 bit each (one 0 or 1; 8 bits = 1 byte):
| Part | Size | What it holds |
|---|---|---|
| Byte 1 | 1 byte | FIN (the last part of the message?) and the opcode (the frame's kind) |
| Byte 2 | 1 byte | MASK (masked or not) and a payload length of 0 to 125 |
| Extra length | 0, 2 or 8 bytes | value 126: the length is in the next 2 bytes (up to 65,535). Value 127: in the next 8 bytes |
| Masking key | 0 or 4 bytes | only in frames from the browser |
The opcodes to know: 1 text, 2 binary, 0 the continuation of a split message, 8 close, 9 ping, A pong. Opcodes and bytes here are written in hex (base 16: 0 to 9, then A to F), so A = 10.
For example, the server sends a 44-byte status to the board, {"type":"status","id":12,"status":"Ironing"}. Here is its frame, byte by byte:
81 2C 7B 22 74 79 70 65 ... (2-byte header + 44-byte payload = 46 bytes)
81: FIN 1 (the message ends in this frame), opcode 1 (text).2C: MASK 0, length 44 (2Cin hex = 44).
A frame from the browser must be masked. The MASK bit becomes 1, so the second byte becomes AC (80 for MASK 1, plus 2C for 44). After it comes a random 4-byte masking key. Then every payload byte is XORed with that key. XOR is an operation on bits that the same key can undo. The whole frame is then 50 bytes. The example in RFC 6455: "Hello" from the server is 81 05 48 65 6c 6c 6f. From the browser, with the key 37 fa 21 3d, "Hello" becomes 81 85 37 fa 21 3d 7f 9f 4d 51 58 (the letter H: 48 XOR 37 = 7f). Masking is not encryption, because the key is sent along. It stops an old proxy from being tricked into storing bytes an attacker picked. Encryption comes from wss://.
Measured in Chromium 147, Firefox 146 and WebKit 26.4: the header of a browser frame is 6 bytes for a 44-byte message, 8 for 200 bytes, and 14 for 70,000 bytes. Because each side sends its own frames at any time, without waiting for a turn, WebSocket is called full-duplex.
Ping, pong and closing the connection
- Ping (opcode 9) is a frame that asks "still there?". The answer is a pong (opcode A) with the same payload. The browser answers a server's ping automatically (tested: ping
p1answered with pongp1). But JavaScript in the browser cannot send a ping, because there is nows.ping(). On the server, thewslibrary for Node.js hasws.ping(). - Close (opcode 8) is the frame that closes the connection. It carries a 2-byte code and a short reason:
| Code | Meaning | Example at the laundry |
|---|---|---|
| 1000 | closed normally, on purpose | Mrs. Rini presses "Log out" |
| 1001 | going away | the realtime server restarts, or the tab goes to another page (all three browsers send 1001) |
| 1006 | dropped without a close frame | the Wi-Fi stops working. This code is never sent, only reported by the browser, with wasClean false (not closed properly) |
| 1008 | broke a rule | a wrong login token |
| 1011 | server error | the server failed to save the status |
In the browser, ws.close() accepts only the codes 1000 or 3000 to 4999. ws.close(1001) throws an InvalidAccessError. A reason longer than 123 bytes throws a SyntaxError.
The WebSocket API in the browser
This is how you use WebSocket in the browser:
const ws = new WebSocket('ws://localhost:3000/board')
console.log(ws.readyState) // 0: CONNECTING
ws.onopen = () => {
ws.send(JSON.stringify({ type: 'status', id: 12, status: 'Ironing' }))
}
ws.onmessage = (event) => {
const message = JSON.parse(event.data)
console.log(message.id, message.status) // 12 Ironing
}
ws.onclose = (event) => console.log('closed', event.code, event.wasClean)
ws.onerror = () => console.log('error') // no details, close follows
onopenruns when the connection opens,onmessagewhen a message arrives (its content is inevent.data),onclosewhen the connection closes, andonerrorwhen something goes wrong.readyStateis the state of the connection: 0 CONNECTING, 1 OPEN, 2 CLOSING, 3 CLOSED.send()beforeopenthrows anInvalidStateError. After CLOSED,send()stays quiet and the message is thrown away.bufferedAmount: bytes already passed tosend()but not yet sent. Measured: right after sending about 1 MB it read 1,070,246, and half a second later 0 on localhost. Check it before you send a lot of data over a slow network.- Text messages arrive as strings. Binary messages (raw bytes, a photo for example) arrive as a
Blob, or as anArrayBufferwhenws.binaryType = 'arraybuffer'.
On the server, you can use the ws library in Node.js. This server passes every message that arrives on to every connected screen:
import { WebSocketServer } from 'ws'
const wss = new WebSocketServer({ port: 3000, path: '/board' })
wss.on('connection', (ws) => {
ws.on('message', (data) => {
for (const screen of wss.clients) screen.send(String(data)) // pass it on to every screen
})
})
wss here is the name of the server variable, not the address wss://. wss.clients holds every open connection.
Reconnecting: write it yourself, with backoff and jitter
The browser does not reconnect a WebSocket. Tested in all three browsers: after the connection was cut, readyState stopped at 3 and no new handshake came. You write the code yourself: the function connect below calls itself again after the connection closes.
function connect(attempt = 0) {
const ws = new WebSocket('ws://localhost:3000/board')
ws.onopen = () => { attempt = 0 }
ws.onmessage = (event) => show(JSON.parse(event.data))
ws.onclose = (event) => {
if (event.code === 1000) return // closed on purpose
const cap = Math.min(30000, 1000 * 2 ** attempt) // 1, 2, 4, 8, 16, then 30 seconds
const delay = Math.random() * cap // jitter: random between 0 and the cap
setTimeout(() => connect(attempt + 1), delay)
}
}
connect()
- Backoff: the cap on the wait doubles after every failure (
2 ** attemptmeans 2 to the power ofattempt), up to 30 seconds, so a dead server is not flooded. - Jitter: the wait is random. Without it, when the server restarts every board reconnects at exactly the same second (1, then 2, then 4) and they all flood the server together.
onopensetsattemptback to 0, so the next drop starts from a short wait again.
⚠️ First mistakes with WebSocket
send()beforeopen. The result is an instantInvalidStateError. Send insideonopen, or checkws.readyState === WebSocket.OPENfirst.- Thinking the browser reconnects by itself. The board stays silent forever after a short Wi-Fi drop.
ws://on anhttps://page. Blocked. Usewss://.- Reconnecting without jitter. Hundreds of screens flood the freshly restarted server in the same second.
TL;DR: WebSocket starts with a handshake, an opening HTTP request with Upgrade: websocket and Sec-WebSocket-Key (a random key). The server answers 101 Switching Protocols with Sec-WebSocket-Accept = base64(SHA-1(key + GUID)): a value computed from that key and a fixed text (the GUID), for example s3pPLMBiTxaQ9kYGzzhZRbK+xOo=. After that the connection uses the WebSocket protocol (ws:// or wss://), not HTTP. Messages travel in frames (the wrapper around each message). A frame's header holds an opcode, the frame's kind (1 text, 2 binary, 8 close, 9 ping that asks "still there?", A pong), the message length (7 bits, plus 2 or 8 more bytes when its value is 126 or 127), and a 4-byte masking key (a key that hides the content) on frames from the browser. Full-duplex means both sides can send at the same time without waiting for a turn. Close codes: 1000 normal, 1001 going away, 1006 dropped without a close, 1008 broke a rule, 1011 server error. The browser API: readyState 0 to 3, onopen, onmessage, onclose, onerror, send(), close(), bufferedAmount. The browser does not reconnect: write the reconnect with backoff (waits that double) and jitter (waits made random).
⚡ Handshake: HTTP asks to switch protocols
Guess first: WebSocket starts with an HTTP request that carries a random key, Sec-WebSocket-Key. What must the server put in Sec-WebSocket-Accept: the same key, a new random key, or a value computed from that key?
A value computed from that key: the key is joined with the GUID (a fixed text from RFC 6455, the WebSocket standard), turned by SHA-1 into a 20-byte fingerprint, then written in base64 (letters and digits). If the result differs from the browser's own calculation, the connection fails.
Meaning: The connection starts as an ordinary HTTP request with Upgrade: websocket. This opening request is called the handshake. The server answers 101 Switching Protocols, and after that the same TCP connection (the network connection) no longer speaks HTTP.
⚡ Full-duplex: like a phone
Meaning: The browser and the server can send at the same moment, without waiting for their turn, like two people on a phone, not in turns like a walkie-talkie. This is called full-duplex. Each message is wrapped in a frame (a small wrapper) with a small header, not HTTP headers.
⚡ Send after open
Write:
const ws = new WebSocket('ws://localhost:3000/board')
console.log(ws.readyState) // 0: CONNECTING
ws.onopen = () => {
ws.send(JSON.stringify({ type: 'status', id: 12, status: 'Ironing' }))
}
Meaning: new WebSocket(...) starts connecting, and readyState (the state of the connection) is still 0: CONNECTING. send() before the connection is open throws an InvalidStateError. So send the message inside onopen, the function that runs once the connection is open.
⚡ Reconnecting: write it yourself
Meaning: The browser does not reconnect a WebSocket that dropped: you write the reconnect code yourself. Use backoff (the cap on the wait doubles after every failure, up to 30 seconds) and jitter (the wait is random), so a freshly restarted server is not flooded by every screen in the same second.