← All lessons
How WebSockets work
Upgrade a request into a WebSocket
Browser
chat.test
browser.js
// the browser runs the handshake for youconst ws = new WebSocket("wss://chat.test/room");// it checks Sec-WebSocket-Accept before onopenws.onopen = () => ws.send("hello");ws.onmessage = (e) => console.log(e.data);server.js
const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; server.on("upgrade", (req, socket) => { const key = req.headers["sec-websocket-key"]; const accept = base64(sha1(key + GUID)); socket.write( "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\nConnection: Upgrade\r\n" + `Sec-WebSocket-Accept: ${accept}\r\n\r\n`, ); // the socket stays open for frames});Talk both ways over the open line
Ana
Server
Ben
Ana's screen
Ben's screen
browser.js
const ws = new WebSocket("wss://chat.test/room"); form.onsubmit = () => ws.send(input.value);ws.onmessage = (e) => addLine(e.data);server.js
wss.on("connection", (ws) => { ws.on("message", (data) => { for (const peer of wss.clients) { if (peer !== ws) peer.send(data); } });}); // nobody asked: the server sends when it has newsmatch.on("goal", (score) => { for (const peer of wss.clients) peer.send(score);});Inside a frame a few bytes of header, then your text
Bytes on the wire
frame.js
function frame(text, fromBrowser) { const payload = new TextEncoder().encode(text); const head = [0x81]; // FIN + opcode 1 (text) head.push((fromBrowser ? 0x80 : 0) | payload.length); if (!fromBrowser) return [...head, ...payload]; const mask = crypto.getRandomValues(new Uint8Array(4)); const masked = payload.map((b, i) => b ^ mask[i % 4]); return [...head, ...mask, ...masked];}Why not just poll? count the requests for one minute
Polling every 5 s
Long polling 30 s timeout
WebSocket one connection
Every HTTP request carries its full headers. A WebSocket frame header is 2 bytes
browser.js
// polling: ask again and againsetInterval(async () => { const res = await fetch("/messages?since=" + last); show(await res.json());}, 5000); // long polling: the server holds the request until there's newswhile (true) { const res = await fetch("/messages/wait"); show(await res.json());} // WebSocket: one request, then the server pushesconst ws = new WebSocket("wss://chat.test/room");ws.onmessage = (e) => show(e.data);Topics
Next: How database indexes work
Open lesson