Loading

T9 APIs · Lesson 7

WebSockets

One request opens a line that stays open, and after that either side may speak at any moment. Serve WebSockets with the ws package beside an Express app, connect with the WebSocket class that browsers and Node share, send text, JSON and bytes, reach every client at once, and keep the line honest with close codes and pings.

  • say what a WebSocket is, how the handshake turns an HTTP request into an open line, and when to use one instead of requests
  • run a WebSocket server with the ws package, on its own or beside an Express app, and connect to it with the WebSocket class that browsers and Node share
  • send and receive text, JSON with a type field, and binary messages, and know what arrives on each side
  • keep every connected client in a set, broadcast to all of them, and answer one of them
  • close a connection with a code and a reason, read them on the other side, and handle a line that fails to open
  • keep the line honest with ping and pong, and reconnect when it breaks
About 70 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-15); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-15); ws, the WebSocket server package from npm (the kit compares every WebSocket block with it, in its sandbox; the page runs the small ws of plan 25) 8.23.0 (2026-11-15)Play this lesson's games

The back cover

Couriers carry one parcel each way and then leave. Some news cannot wait for a courier to be sent: a gauge that spikes, a message from a friend, a score that changes. For that, the yard keeps a pneumatic tube open between two desks, and either side can drop a capsule in at any moment.

These pages open such a tube on the web: the WebSocket. They show the handshake that turns an HTTP request into an open line, and a server that shares Express's port. They send messages both ways and news to many listeners at once, and they show how a line ends, breaks and comes back.

Before you start

The story: Couriers asking for nothing

The Engine Hall wants to know the boiler's reading the moment it changes. So every minute, a courier runs to the yard with the same question: anything new? Most minutes the answer is no, and the courier runs back with an empty parcel.

By noon the belt is clogged with empty parcels, and when the reading does change, the news still waits for the next courier.

Yardmaster Waybill looks at the queue of runners asking for nothing. "Lay a speaking tube between the two halls," she says. "One request to open it, and after that either end may speak at any moment: no parcel, no address, no stamp. Learn to lay the tube, keep it open, and know when it has gone quiet."

Everything in this track so far was a question and an answer. The client asks, the server answers, the connection is done with. That fits a form, a page or a reading fetched once. It does not fit a gauge that a page must show the moment it changes, a chat, or a game.

A WebSocket is one connection that stays open, on which both sides may send at any moment. This lesson opens one from a page or a program, serves it beside an Express app, sends messages of three kinds, reaches many clients at once, and keeps the line healthy.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
HTTP requests and headers.Upgrade: websocketThe handshake that opens the line.
An Express app and its server.const server = app.listen(3000)A WebSocket server beside the routes.
npm packages.npm install wsThe ws package.
Events and listeners.socket.on("message", fn)Everything a connection does.
JSON.JSON.stringify({ type: ... })Messages with a type.
Buffers and bytes.Buffer.from([1, 2, 3])Binary messages.
Sets and loops.for (const client of wss.clients)Broadcast.
Status codes.101, 426The handshake's answers.
Timers.setIntervalA ping that keeps the line honest.
Error handling.ws.onerrorA line that fails to open, or breaks.

By the end of this lesson you will be able to:

  • say what a WebSocket is, how the handshake turns an HTTP request into an open line, and when to use one instead of requests;
  • run a WebSocket server with the ws package, on its own or beside an Express app, and connect to it with the WebSocket class that browsers and Node share;
  • send and receive text, JSON with a type field, and binary messages, and know what arrives on each side;
  • keep every connected client in a set, broadcast to all of them, and answer one of them;
  • close a connection with a code and a reason, read them on the other side, and handle a line that fails to open;
  • keep the line honest with ping and pong, and reconnect when it breaks.

How to follow this lesson

Every block is a WebSocket server and its own client in one program, as the Express lessons' blocks were a server and a client. It runs on the page in the small Node with its small ws, and it has also been run with the real ws 8.23.0 in real Node 22, where it prints the same.

Lines from the server and from the client come in the order the events fired, which is the order the two sides heard each other. When the order matters, the text says why it is what it is.

In one line

A WebSocket is one connection that stays open after a single HTTP handshake, on which either side may send a message at any moment; the ws package serves it, and the WebSocket class connects to it.

A line that stays open

At a glance

HTTP is a conversation where the client always speaks first. Some news cannot wait to be asked for.

A WebSocket starts as one ordinary HTTP request, with the header Upgrade: websocket and a random key. A server that agrees answers 101, with an accept value made from the key. From then on the line stays open, and either side may send a message at any moment, with no new request. Use one when the server must speak first, such as for a live gauge or a chat.

Take a guess: How did servers push news before WebSockets existed?

Every request in this track was one question and one answer. For a gauge that a page must show the moment it changes, that is the wrong shape: the page would have to ask again and again, and most answers would say nothing new. The server knows when the reading changes; it should be able to speak first.

A WebSocket is a connection that stays open. It begins as one HTTP request, and after that request is answered, the connection is no longer HTTP: it is a line on which either side may send a message at any moment, until one side closes it. Here is the smallest one, a server and a client in one program:

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => {
  socket.on("message", (data) => socket.send("echo: " + data));
});
const ws = new WebSocket("ws://localhost:3000");
ws.onopen = () => ws.send("hello");
ws.onmessage = (event) => {
  console.log(event.data);
  ws.close();
};
ws.onclose = () => wss.close();

Terminal: node app.js

echo: hello

The server comes from the ws package: new WebSocketServer({ port: 3000 }) listens, and its connection event hands over a socket for each client that connects. The client is the WebSocket class, which browsers have had for years and Node has since version 22: new WebSocket("ws://localhost:3000") opens the line.

Read the order. The client could not send until the line was open, so it sent hello from its open handler. The server's socket heard a message event and sent an answer on the same line. The client heard a message event, printed it, and closed. The address starts with ws://, the WebSocket's own scheme, and wss:// is its version over TLS, as https is to http.

SideClassHearsDoes
servera socket from WebSocketServer's connection eventmessage, close, error, ping, pongsend, close, ping
clientWebSocket, the same in browsers and Nodeopen, message, close, errorsend, close

The handshake

How does one HTTP request become an open line? The client sends a GET with two extra headers, Upgrade: websocket and Connection: Upgrade, a random key, and the protocol's version. A server that agrees answers 101 Switching Protocols, and from that moment both sides stop speaking HTTP. ws lets you watch it through the headers event:

app.js

const { WebSocketServer } = require("ws");
const crypto = require("crypto");
const wss = new WebSocketServer({ port: 3000 });
wss.on("headers", (headers, req) => {
  console.log("the request asked:", req.headers.connection, "|", req.headers.upgrade, "| version", req.headers["sec-websocket-version"], "| key length", req.headers["sec-websocket-key"].length);
  const expected = crypto.createHash("sha1").update(req.headers["sec-websocket-key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
  console.log("the server answers:", headers.slice(0, 3).join(" ; "), "; accept as computed:", headers[3] === "Sec-WebSocket-Accept: " + expected);
});
wss.on("connection", (socket) => socket.close());
const ws = new WebSocket("ws://localhost:3000");
ws.onclose = () => wss.close();

Terminal: node app.js

the request asked: upgrade | websocket | version 13 | key length 24
the server answers: HTTP/1.1 101 Switching Protocols ; Upgrade: websocket ; Connection: Upgrade ; accept as computed: true

The key is 16 random bytes in base64, 24 characters. The server does not send the key back; it sends an accept value made from the key: the key, then a fixed string from the standard, hashed with SHA-1 and written in base64. The client checks it, which proves that the server understood the handshake and did not answer by accident. Here is that sum, on the example key from the standard itself:

app.js

const crypto = require("crypto");
const key = "dGhlIHNhbXBsZSBub25jZQ==";
const accept = crypto.createHash("sha1").update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
console.log(accept);

Terminal: node app.js

s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

The answer matches the standard's example, as it must: the same key always gives the same accept value. Node's crypto module does the hashing; the fixed string, 258EAFA5-E914-47DA-95CA-C5AB0DC85B11, is written into every WebSocket server in the world.

Line of the handshakeSent byMeaning
GET /live HTTP/1.1 with Upgrade: websocketthe clientplease turn this connection into a WebSocket
Sec-WebSocket-Key: a random keythe clientprove you understood
Sec-WebSocket-Version: 13the clientthe version of the protocol, the only one in use
HTTP/1.1 101 Switching Protocolsthe serveragreed: this connection is now a WebSocket
Sec-WebSocket-Accept: the sumthe serverthe proof, from the key and the fixed string

A plain request to a WebSocket server, with no Upgrade header, is refused with 426 Upgrade Required, whatever the path:

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000, path: "/live" });
(async () => {
  const r = await fetch("http://localhost:3000/other");
  console.log(r.status, JSON.stringify(await r.text()));
  const l = await fetch("http://localhost:3000/live");
  console.log(l.status, JSON.stringify(await l.text()));
  wss.close();
})();

Terminal: node app.js

426 "Upgrade Required"
426 "Upgrade Required"

When to use one

Requests are the right shape when the client knows when to ask: a page load, a form, a reading fetched once. A WebSocket is the right shape when the server knows when there is news, or when the two sides talk often. Think of a gauge that changes, a chat, a game, a log that scrolls, or a document edited by two people at once.

It costs something. Every open line is a connection the server keeps, with its memory; a line can break and must be reopened; and caches, which help every GET, cannot help a line. Use requests by default, and a WebSocket where the server must speak first.

Worked example 1

Show a reading the moment it changes: a server that pushes the boiler's reading on connection and again each time it changes, and a client that prints what the page would show.

What we have: a WebSocket server with a reading in a variable, and a timer that changes it three times

What we need: four lines, 95 to 98, each printed the moment the server sent it

The plan: send the reading once on connection, then from the timer; close the socket after the last change, and close the server when the client hears close

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
let boiler = 95;
wss.on("connection", (socket) => {
  socket.send(`boiler ${boiler}`);
  const changes = setInterval(() => {
    boiler += 1;
    socket.send(`boiler ${boiler}`);
    if (boiler === 98) { clearInterval(changes); socket.close(); }
  }, 20);
});
const ws = new WebSocket("ws://localhost:3000");
ws.onmessage = (event) => console.log("the page shows:", event.data);
ws.onclose = () => wss.close();

Terminal: node app.js

the page shows: boiler 95
the page shows: boiler 96
the page shows: boiler 97
the page shows: boiler 98
  1. The client never asked. It opened the line and printed whatever arrived, four times, as the server chose to speak.
  2. With requests, the page would have asked every second and received 95 many times before 96 came; here it received each reading once, at once.
  3. The server closed the socket when it was done, and the client, hearing close, closed the server, so that the program ended.

boiler 95, then 96, 97 and 98, each as it changed.

Check: Four messages for four readings, with nothing asked in between.

Another way: send the reading as JSON, { gauge: "boiler", value: 96 }, so that a page can tell readings from other messages; the next sections do that.

A path that fails: sending the reading from a route and asking the page to fetch it every second. The page would fetch 50 times for 4 changes, and still show each change up to a second late.

When you are stuck: The line does not open

Is the address ws://, with the server's port? A WebSocket client cannot connect with http://.

Did you send before open? A WebSocket throws if you send while it is still connecting; send from the open handler.

Is a WebSocket server attached? An Express app alone answers no handshake, and the client's error event fires.

Your turn

Which status does a server answer to agree to a WebSocket handshake, and which to refuse a plain request?Tap to reveal
  1. One switches protocols; the other asks for an upgrade.

101 Switching Protocols to agree; 426 Upgrade Required for a plain request.

What is Sec-WebSocket-Accept made from?Tap to reveal
  1. Two things, hashed, then written in base64.

The client's key plus the fixed string from the standard, hashed with SHA-1, in base64.

cat > app.js <<'END'
const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => socket.send("first word"));
const ws = new WebSocket("ws://localhost:3000");
ws.onmessage = (event) => { console.log(event.data); ws.close(); };
ws.onclose = () => wss.close();
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
first word
  1. The server sends as soon as the line opens.
  2. The client prints the message, then closes the line and the server.

It prints first word.

Did you know?

Pushing before WebSockets

Before WebSockets, servers pushed news by bending HTTP. RFC 6202, of April 2011, describes the two common ways, long polling and streaming. In long polling, the server holds each request open and answers only when it has news, so a request is always waiting. Its abstract says that HTTP is often used, some would say abused, for such messages.

Why it fits here: It answers this topic's question: before WebSockets, long polling kept a request waiting until the server had news.

Source: RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP

A standard in 2011, and over HTTP/2 in 2018

The WebSocket protocol became a standard in December 2011, as RFC 6455, and its handshake is an upgrade of an HTTP/1.1 request. HTTP/2 has no such upgrade, so in September 2018 RFC 8441 defined a way to run the WebSocket protocol over a single stream of an HTTP/2 connection instead.

Why it fits here: It dates this topic's handshake: RFC 6455 of 2011, joined in 2018 by a way to carry WebSockets over HTTP/2.

Sources: RFC 6455: The WebSocket Protocol; RFC 8441: Bootstrapping WebSockets with HTTP/2

In one line

A WebSocket starts as one HTTP request with Upgrade: websocket and a random key. A server that agrees answers 101 with an accept value hashed from the key, and from then on either side may send a message at any moment. Use one when the server must speak first.

A server beside the routes

At a glance

A WebSocket server can share the port of an Express app. One server then answers both kinds of request.

The call new WebSocketServer({ server, path }) attaches the ws package to Express's own http server. Node fires the upgrade event for a handshake and the request event for everything else, so each goes to the right place. The connection event brings each new socket, with the handshake's request. A socket's readyState walks from 0 to 3 as the line opens, stays open, starts closing and closes.

Take a guess: Can a Socket.IO client talk to a plain WebSocket server?

The ws package comes from npm, as Express did. In the shop's folder, one install brings it; it has no packages of its own:

Measured in a real terminal on 2026-11-15, with Node 22.23.1 and npm 10.9.8

asha@tower:~/shop$ npm install ws

added 1 package, and audited 67 packages in 648ms

30 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

asha@tower:~/shop$ npm ls ws
express-vendor@ /home/rohan-laptop/.cache/study/vendor/express5
└── ws@8.23.0

The blocks on this page skip the install: the page's small Node holds a small ws of its own, and the kit's sandbox holds the real one, so require("ws") works in both.

An API seldom runs a WebSocket server on a port of its own. The page that opens the line came from the same server as the API, and one port is simpler to run, to secure and to put behind a proxy. ws can share Express's server: new WebSocketServer({ server }) instead of a port. The server keeps answering requests, and ws takes only the requests that ask to upgrade:

app.js

const express = require("express");
const { WebSocketServer } = require("ws");
const app = express();
app.get("/", (req, res) => res.send("the page"));
const server = app.listen(3000, async () => {
  console.log("http:", await (await fetch("http://localhost:3000/")).text());
  const ws = new WebSocket("ws://localhost:3000/live");
  ws.onopen = () => ws.send("hello from the client");
  ws.onmessage = (event) => { console.log("client got:", event.data); ws.close(); };
  ws.onclose = () => server.close();
});
const wss = new WebSocketServer({ server, path: "/live" });
wss.on("connection", (socket, req) => {
  console.log("server: a connection on", req.url);
  socket.on("message", (data) => {
    console.log("server got:", data.toString());
    socket.send("welcome");
  });
});

Terminal: node app.js

http: the page
server: a connection on /live
server got: hello from the client
client got: welcome

app.listen(3000) returns Node's http server, the same object lesson 01 made with http.createServer. Express listens for its request event, and ws listens for its upgrade event: Node fires upgrade instead of request when a request carries Upgrade: websocket. So the GET went to Express and the handshake to ws, on one port.

The path option keeps ws to one address, /live; a handshake on any other path is refused. The connection event's second argument is the handshake's request, with its url and its headers, and the program printed req.url.

new WebSocketServer(...)Listens onPlain requests
{ port: 3000 }a server ws makes itselfanswered 426 Upgrade Required
{ server }your http server, on its portanswered by your app as before
{ server, path: "/live" }the same, for handshakes on /live onlyanswered by your app; other paths refused the handshake

The order of events

Two programs run in one here, so the order of the lines teaches as much as the lines. This block prints every step on both sides, with readyState, the number that says where the client's line stands:

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => {
  console.log("server: connection; clients:", wss.clients.size);
  socket.on("message", (data, isBinary) => console.log("server: message", JSON.stringify(data.toString()), "binary:", isBinary, "| type:", data.constructor.name));
  socket.on("close", (code, reason) => { console.log("server: close", code, JSON.stringify(reason.toString())); wss.close(); });
});
const ws = new WebSocket("ws://localhost:3000");
console.log("client: readyState after new:", ws.readyState, "url:", ws.url);
ws.addEventListener("open", () => { console.log("client: open; readyState:", ws.readyState, "protocol:", JSON.stringify(ws.protocol)); ws.send("one"); ws.send("two"); ws.close(4000, "done for today"); console.log("client: readyState after close():", ws.readyState); });
ws.addEventListener("close", (event) => console.log("client: close", event.code, JSON.stringify(event.reason), "wasClean:", event.wasClean, "readyState:", ws.readyState));

Terminal: node app.js

client: readyState after new: 0 url: ws://localhost:3000/
server: connection; clients: 1
client: open; readyState: 1 protocol: ""
client: readyState after close(): 2
server: message "one" binary: false | type: Buffer
server: message "two" binary: false | type: Buffer
client: close 4000 "done for today" wasClean: true readyState: 3
server: close 4000 "done for today"

Read it from the top. new WebSocket returns at once with readyState 0, CONNECTING, while the handshake is still on its way. The server saw the connection first, then the client's open event fired, with readyState 1, OPEN.

Inside the open handler the client sent two messages and called close with a code and a reason, and its readyState became 2, CLOSING, at once. The server heard the two messages, as Buffers, then the client heard its close event, wasClean true and readyState 3, and last the server heard its close, with the same code and reason.

readyStateNameMeaning
0CONNECTINGthe handshake is on its way; send throws
1OPENthe line is open; send and close work
2CLOSINGclose was called, or the other side asked; nothing more is sent
3CLOSEDthe line is gone; the close event has fired

The server side has the same four numbers on its sockets, and the ws package exports them as WebSocket.OPEN and the others, which the broadcast section uses.

Worked example 2

Greet each client by what its handshake carried: the hall named in the address's query string, and the address it connected from, while the same server keeps answering the API's routes.

What we have: an Express app with a /gauges route, and ws on the same server at /live

What we need: the route's JSON, then a greeting that names the hall and the client's address

The plan: read req.url in the connection event, parse its query with the URL class, read req.socket.remoteAddress, and send one message

app.js

const express = require("express");
const { WebSocketServer } = require("ws");
const app = express();
app.get("/gauges", (req, res) => res.json({ boiler: 95 }));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges");
  console.log("GET /gauges:", await r.text());
  const ws = new WebSocket("ws://localhost:3000/live?hall=engine");
  ws.onmessage = (event) => { console.log("client got:", event.data); ws.close(); };
  ws.onclose = () => server.close();
});
const wss = new WebSocketServer({ server, path: "/live" });
wss.on("connection", (socket, req) => {
  const hall = new URL(req.url, "http://localhost").searchParams.get("hall");
  const from = req.socket.remoteAddress;
  socket.send(`welcome, ${hall}, connected from ${from}`);
});

Terminal: node app.js

GET /gauges: {"boiler":95}
client got: welcome, engine, connected from ::ffff:127.0.0.1
  1. The handshake's request is a request like any other: its url carried the query string, and its socket knows where the client is.
  2. The address is IPv4's 127.0.0.1 written inside IPv6, as lesson 05 showed for req.ip: Node's server listens on both.
  3. The GET to /gauges never touched ws, and the handshake never touched Express's routes.

GET /gauges answered by Express, then welcome, engine, connected from ::ffff:127.0.0.1 over the line.

Check: Two protocols, one port, and the handshake's request told the server who was calling.

Another way: check a token in the query string, or a cookie in req.headers.cookie, before accepting: a page's cookies ride along with the handshake, as with any request to the same site.

A path that fails: trusting the hall name for anything that matters. It came from the client's address bar; a guard should check a key or a cookie, as lesson 04 did for routes.

When you are stuck: The handshake is refused, or the route stopped answering

Does the client's path match the path option? /live and /live/ are different paths.

Is ws given the server that app.listen returned, not the app? new WebSocketServer({ server: app }) has no upgrade event to listen to.

Did a route answer the handshake? Express never sees an upgrade request, so a route cannot; check the client's address and port.

Your turn

Which event of Node's http server does ws listen for, and which one does Express listen for?Tap to reveal
  1. A request that asks to change protocol fires a different event.

ws listens for upgrade; Express for request.

A client calls send right after new WebSocket, before the open event. What happens?Tap to reveal
  1. Look at readyState 0.

It throws: the line is still CONNECTING; send from the open handler.

cat > app.js <<'END'
const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => socket.close(1000, "bye"));
const ws = new WebSocket("ws://localhost:3000");
ws.onclose = (event) => { console.log(event.code, event.reason, ws.readyState); wss.close(); };
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
1000 bye 3
  1. The server closes with a code and a reason as soon as the line opens.
  2. In the client's close event, readyState is already 3, CLOSED.

It prints 1000 bye 3.

Did you know?

Socket.IO is not a WebSocket

Socket.IO, a popular library above WebSockets, is not itself a WebSocket. Its documentation says so in capitals: Socket.IO is NOT a WebSocket implementation. It uses WebSocket for transport when it can, but adds metadata to each packet, so a WebSocket client cannot connect to a Socket.IO server, and a Socket.IO client cannot connect to a plain WebSocket server.

Why it fits here: It answers this topic's question: Socket.IO speaks its own format, so it cannot talk to a plain WebSocket server.

Source: Socket.IO documentation: Introduction

Node's own WebSocket is a client

Node has a WebSocket class of its own, but for one side only. Its manual says the global WebSocket was added in Node 21.0.0 and 20.10.0 and stopped being experimental in 22.4.0. The Node.js site explains that it lets Node act as a WebSocket client without libraries like ws, for client connections; a server still comes from a package, such as ws.

Why it fits here: It adds to this topic's server: Node's built-in WebSocket only connects, so serving still needs ws.

Sources: Node.js manual: Globals (WebSocket); Node.js: WebSocket client

In one line

new WebSocketServer({ server, path }) shares Express's http server: Node fires upgrade for a handshake and request for everything else. The connection event brings the handshake's request, and readyState walks from 0 to 3 as the line opens and closes.

Messages: text, JSON and bytes

At a glance

Down an open line go messages, and a message is text or bytes with no label at all.

So programs agree on a language, usually JSON with a type field, and answer in the same one. On the server, a message arrives as a Buffer, with isBinary saying whether it was bytes. On the client, it is a string or a Blob. Parse every message inside try, because a throw inside a listener ends the whole process. One bad message must never end the server for everyone.

Take a guess: Does a browser send its WebSocket messages exactly as they were written?

A message on a WebSocket is a parcel with no label: it has no address, no method and no headers, only its contents, which are text or bytes. The line carries them in order, whole, one at a time. What a message means is for the program to decide.

So every program that uses WebSockets invents a small language of its own. The usual one is JSON with a type field, which says what kind of message this is, as the method and the path did for a request:

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
const gauges = { boiler: 95 };
wss.on("connection", (socket) => {
  socket.on("message", (data) => {
    const message = JSON.parse(data);
    if (message.type === "read") socket.send(JSON.stringify({ type: "reading", gauge: message.gauge, value: gauges[message.gauge] ?? null }));
    else if (message.type === "set") { gauges[message.gauge] = message.value; socket.send(JSON.stringify({ type: "saved", gauge: message.gauge })); }
    else socket.send(JSON.stringify({ type: "error", message: `no such type: ${message.type}` }));
  });
});
const ws = new WebSocket("ws://localhost:3000");
const outgoing = [{ type: "read", gauge: "boiler" }, { type: "set", gauge: "fan", value: 40 }, { type: "read", gauge: "fan" }, { type: "dance" }];
ws.onopen = () => { for (const m of outgoing) ws.send(JSON.stringify(m)); };
let count = 0;
ws.onmessage = (event) => {
  console.log(event.data);
  if (++count === outgoing.length) ws.close();
};
ws.onclose = () => wss.close();

Terminal: node app.js

{"type":"reading","gauge":"boiler","value":95}
{"type":"saved","gauge":"fan"}
{"type":"reading","gauge":"fan","value":40}
{"type":"error","message":"no such type: dance"}

The client sent four JSON messages in a row, from its open handler, and the server answered each in order. The server read each message's type and did one thing for read, another for set, and sent an error message, in the same language, for a type it did not know.

Notice what replaced what. The type replaced the method and the path; the other fields replaced the query and the body; the answer's type replaced the status code. There is no status on a line, so the answer must say in its own words whether it succeeded.

With requestsOn a WebSocket
the method and the patha type field
the query and the bodythe message's other fields
the status codean answering type, such as saved or error
one answer for one requestany number of messages, either way, in any order

What arrives on each side

The two sides see a message differently. On the server, ws hands the message event a Buffer and a flag, isBinary, which says whether the sender called it bytes or text. On the client, a text message arrives as a string, and bytes arrive as a Blob, a bundle of bytes with an arrayBuffer method:

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => {
  socket.on("message", (data, isBinary) => console.log("server got", data.length, "bytes, binary:", isBinary, Array.from(data)));
  socket.send("text");
  socket.send(Buffer.from([1, 2, 3]));
});
const ws = new WebSocket("ws://localhost:3000");
console.log("binaryType:", ws.binaryType);
let n = 0;
ws.onmessage = async (event) => {
  const data = event.data;
  console.log("client got:", data.constructor.name, typeof data === "string" ? JSON.stringify(data) : Array.from(new Uint8Array(await data.arrayBuffer())));
  if (++n === 2) { ws.send(new Uint8Array([9, 8])); ws.close(); }
};
ws.onclose = () => wss.close();

Terminal: node app.js

binaryType: blob
client got: String "text"
client got: Blob [ 1, 2, 3 ]
server got 2 bytes, binary: true [ 9, 8 ]

The server sent a string and three bytes. The client got the string as a String, and the bytes as a Blob, which it unpacked with await data.arrayBuffer(). Then the client sent two bytes, as a Uint8Array, and the server got a Buffer of two with isBinary true.

A Blob is the browser's way with bytes; setting ws.binaryType = "arraybuffer" makes bytes arrive as an ArrayBuffer instead, with no await. On the server, data.toString() turns a text message's Buffer into its string, and lesson 02's rule stands: JSON.parse needs a string, and a Buffer becomes one on the way in.

Sent asThe server's message eventThe client's message event
a stringa Buffer, isBinary falsea string
a Buffer, a Uint8Array or an ArrayBuffera Buffer, isBinary truea Blob, or an ArrayBuffer with binaryType set

Text for people and programs, bytes for pictures and sound

JSON text serves almost every API: readings, chat, positions in a game. Bytes are for what is already bytes, such as a picture, a sound sample or a file's part. Mixing both on one line is fine; isBinary and the data's type tell them apart.

Worked example 3

Route messages by type through a table of handlers, give every message an id that its answer carries back, and answer broken JSON and unknown types with error messages.

What we have: a gauges object, a handlers table with list, set and read, and five messages from the client, one of them not JSON

What we need: an answer for each message, carrying its id, and two error messages

The plan: parse inside try; look the type up in the table; spread the handler's answer and add the id; send an error for a parse failure or a missing handler

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
const gauges = { boiler: 95, fan: 40 };
const handlers = {
  read: (m) => ({ type: "reading", gauge: m.gauge, value: gauges[m.gauge] ?? null }),
  list: () => ({ type: "gauges", names: Object.keys(gauges) }),
  set: (m) => { gauges[m.gauge] = m.value; return { type: "saved", gauge: m.gauge, value: m.value }; },
};
wss.on("connection", (socket) => {
  socket.on("message", (data) => {
    let message;
    try { message = JSON.parse(data); } catch { return socket.send(JSON.stringify({ type: "error", message: "not JSON" })); }
    const handle = handlers[message.type];
    if (!handle) return socket.send(JSON.stringify({ type: "error", message: `no such type: ${message.type}` }));
    socket.send(JSON.stringify({ ...handle(message), id: message.id }));
  });
});
const ws = new WebSocket("ws://localhost:3000");
const outgoing = ['{"id":1,"type":"list"}', '{"id":2,"type":"set","gauge":"fan","value":45}', '{"id":3,"type":"read","gauge":"fan"}', "not json at all", '{"id":5,"type":"fly"}'];
ws.onopen = () => { for (const m of outgoing) ws.send(m); };
let count = 0;
ws.onmessage = (event) => {
  console.log(event.data);
  if (++count === outgoing.length) ws.close();
};
ws.onclose = () => wss.close();

Terminal: node app.js

{"type":"gauges","names":["boiler","fan"],"id":1}
{"type":"saved","gauge":"fan","value":45,"id":2}
{"type":"reading","gauge":"fan","value":45,"id":3}
{"type":"error","message":"not JSON"}
{"type":"error","message":"no such type: fly"}
  1. A table of handlers replaces a chain of ifs, and adding a type means adding one line to the table.
  2. The id lets a client match an answer with its question when many are in flight; the two errors have no id, because the broken message had none and the unknown type's id was left out.
  3. try around JSON.parse keeps one bad message from crashing the server: on a line, one client's mistake must never end the program for everyone else.

gauges, saved, reading, then two error messages, in the order sent.

Check: Each answer carried the id of its message; the two bad messages got errors in the same language.

Another way: put the error's id in too, when the message had one, so that a client can match the error with the question that caused it.

A path that fails: letting JSON.parse throw. A throw inside a message listener is a throw inside a callback, which lesson 06 showed ends the process.

Worked example 4

Give the client a question-and-answer helper on the line: ask(type, fields) sends a message with a fresh id and returns a promise that resolves with the answer carrying that id.

What we have: a server that answers every message with the same id it came with, and a client with a Map from ids to the promises' resolve functions

What we need: three answers, each matched to its question by id, printed in order from an async open handler

The plan: ask stores resolve in the Map under the id and sends; the message handler looks the answer's id up, resolves and forgets it

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
const gauges = { boiler: 95, fan: 40 };
wss.on("connection", (socket) => {
  socket.on("message", (data) => {
    const m = JSON.parse(data);
    const answer = m.type === "read" ? { value: gauges[m.gauge] ?? null } : m.type === "list" ? { names: Object.keys(gauges) } : { error: `no such type: ${m.type}` };
    socket.send(JSON.stringify({ id: m.id, ...answer }));
  });
});
const ws = new WebSocket("ws://localhost:3000");
const waiting = new Map();
let nextId = 1;
function ask(type, fields = {}) {
  const id = nextId++;
  ws.send(JSON.stringify({ id, type, ...fields }));
  return new Promise((resolve) => waiting.set(id, resolve));
}
ws.onmessage = (event) => {
  const answer = JSON.parse(event.data);
  waiting.get(answer.id)(answer);
  waiting.delete(answer.id);
};
ws.onopen = async () => {
  console.log("list:", (await ask("list")).names.join(", "));
  console.log("fan:", (await ask("read", { gauge: "fan" })).value);
  console.log("dance:", (await ask("dance")).error);
  ws.close();
};
ws.onclose = () => wss.close();

Terminal: node app.js

list: boiler, fan
fan: 40
dance: no such type: dance
  1. A line has no request and answer of its own; the id and the Map build one on top of it, so that await works as it did with fetch.
  2. The Map grows by one for each question in flight and shrinks when the answer comes; a real helper also gives up after a timeout, as lesson 06's bell did.
  3. The server did not change for this: it only echoed the id, which is all a server must do for clients to match answers.

list: boiler, fan, fan: 40, dance: no such type: dance.

Check: Three questions, three answers, each matched by its id, with await in a straight line of code.

Another way: reject the promise, instead of resolving it, when the answer has an error field, so that a try and catch around await handles it.

A path that fails: matching answers by order instead of by id. A server that answers one question slowly and the next one fast would hand the answers to the wrong questions.

When you are stuck: The message is not what I expected

A Buffer where you wanted text? On the server, call data.toString() before JSON.parse.

A Blob where you wanted bytes? On the client, await data.arrayBuffer(), or set binaryType to arraybuffer.

An object where you wanted JSON? Call JSON.stringify before send; send turns an object into the text [object Object].

Your turn

On the server, what does the message event receive for a text message, and how do you read it as JSON?Tap to reveal
  1. Look at the type column in the table.

A Buffer, with isBinary false; JSON.parse(data.toString()), or JSON.parse(data), which calls toString itself.

Why does every message carry a type field?Tap to reveal
  1. What took the method's place?

A line has no method or path, so the type says what kind of message it is, and the program branches on it.

cat > app.js <<'END'
const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => socket.on("message", (data) => socket.send(JSON.stringify({ got: JSON.parse(data).n * 2 }))));
const ws = new WebSocket("ws://localhost:3000");
ws.onopen = () => ws.send(JSON.stringify({ n: 21 }));
ws.onmessage = (event) => { console.log(typeof event.data, event.data); ws.close(); };
ws.onclose = () => wss.close();
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
string {"got":42}
  1. JSON.parse(data) turns the Buffer into a string and then into an object.
  2. The answer is sent as text and arrives on the client as a string.

It prints string {"got":42}.

Did you know?

Every client frame is masked

A browser does not send its messages exactly as written. RFC 6455 says that a client must mask all frames it sends to the server, with a 32-bit masking key chosen at random for each frame. The reason was an experiment run while the protocol was being written: it showed attacks that poisoned caching proxies in the wild.

Why it fits here: It answers this topic's question: every frame from a client is masked with a random key, to protect proxies.

Source: RFC 6455: The WebSocket Protocol

100 MiB per message

The ws package caps the size of one message. Its documentation gives the option maxPayload a default of 10,48,57,600 bytes, which is 100 MiB, and says that 0 removes the limit. A server that expects small JSON messages, such as gauge readings, can set a much smaller limit of its own.

Why it fits here: It adds to this topic's messages: ws refuses a message over 100 MiB by default, and maxPayload sets the limit.

Source: ws documentation

In one line

A message is text or bytes with no label, so programs speak JSON with a type field and answer in the same language. On the server a message is a Buffer with isBinary, on the client a string or a Blob. Parse inside try, because a throw in a listener ends the process.

Many clients: broadcast and rooms

At a glance

A chat has many people, and a live board has many viewers. A server often speaks to all of them at once.

The server keeps every open socket in wss.clients. A broadcast loops over that set and sends to each socket whose readyState is OPEN, skipping the sender when that is wanted. For groups, such as a room, a Set of your own holds the room's sockets, and a send to the room loops over that Set alone. When a socket closes, its close event removes it from every set.

Take a guess: What happens to messages sent to a listener on a slow network?

A request has one client; a line has many, all open at once. The server keeps every open socket in wss.clients, a Set, and a message meant for everyone is sent to each of them in turn. That is a broadcast, and it is what a line is for: one reading, every page.

Two clients open lines here; the first speaks, and the server repeats the message to both:

app.js

const { WebSocketServer, WebSocket: ServerSocket } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => {
  socket.on("message", (data) => {
    for (const client of wss.clients) {
      if (client.readyState === ServerSocket.OPEN) client.send(`${wss.clients.size} here: ${data}`);
    }
  });
  socket.on("close", () => { if (wss.clients.size === 0) wss.close(); });
});
const names = ["a", "b"];
const sockets = names.map(() => new WebSocket("ws://localhost:3000"));
let opened = 0, got = 0;
sockets.forEach((ws, i) => {
  ws.onopen = () => { opened += 1; if (opened === 2) sockets[0].send("hello from a"); };
  ws.onmessage = (event) => {
    console.log(names[i] + " got:", event.data);
    got += 1;
    if (got === 2) sockets.forEach((s) => s.close());
  };
});

Terminal: node app.js

a got: 2 here: hello from a
b got: 2 here: hello from a

The loop walks the Set and sends to each client whose readyState is OPEN. The ws package exports that constant on its WebSocket class, imported here under the name ServerSocket, so that it does not shadow the client's global WebSocket. The check matters: a client that is closing is still in the Set for a moment, and sending to it would fail.

Both clients heard the message, the sender included. The program waited for both lines to open before anyone spoke, because a broadcast reaches only the clients that are open when it is sent: a client that connects a second later hears nothing of the past.

The server closed itself from the socket's close event, when the Set was empty. ws removes a socket from wss.clients before the program's own close listener runs, so the size is already right there.

Everyone else, and an answer to one

A chat sends a message to everyone except its sender, and tells the sender that it went. Skip the sender in the loop, and send to the one socket for the one answer:

app.js

const { WebSocketServer, WebSocket: ServerSocket } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => {
  socket.on("message", (data) => {
    socket.send("sent to " + (wss.clients.size - 1) + " other(s)");
    for (const client of wss.clients) {
      if (client !== socket && client.readyState === ServerSocket.OPEN) client.send(data.toString());
    }
  });
  socket.on("close", () => { if (wss.clients.size === 0) wss.close(); });
});
const names = ["a", "b", "c"];
const sockets = names.map(() => new WebSocket("ws://localhost:3000"));
let opened = 0, got = 0;
sockets.forEach((ws, i) => {
  ws.onopen = () => { opened += 1; if (opened === 3) sockets[0].send("the boiler is at 97"); };
  ws.onmessage = (event) => {
    console.log(names[i] + " got:", event.data);
    got += 1;
    if (got === 3) sockets.forEach((s) => s.close());
  };
});

Terminal: node app.js

a got: sent to 2 other(s)
b got: the boiler is at 97
c got: the boiler is at 97

The sender heard only the count; the two others heard the message. One loop and one send, with client !== socket to tell them apart: the socket in the connection event is the one client, and wss.clients is everyone.

WantSend to
everyoneeach client in wss.clients that is OPEN
everyone but the senderthe same, skipping the connection's own socket
one clientthat socket alone: socket.send
a groupyour own Set for the group, the next example

Worked example 5

Give the yard rooms: a client joins the room named in its address, and a message reaches the room's members only.

What we have: a Map from room names to Sets of sockets, filled in the connection event from the query string

What we need: two members of the engine room hear the engine's message; the tower's one member hears the tower's

The plan: add the socket to its room's Set on connection, remove it on close, and send a message to the Set's open members, with the room's name in front

app.js

const { WebSocketServer, WebSocket: ServerSocket } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
const rooms = new Map();
wss.on("connection", (socket, req) => {
  const room = new URL(req.url, "http://localhost").searchParams.get("room");
  if (!rooms.has(room)) rooms.set(room, new Set());
  rooms.get(room).add(socket);
  socket.on("message", (data) => {
    for (const member of rooms.get(room)) {
      if (member.readyState === ServerSocket.OPEN) member.send(`[${room}] ${data}`);
    }
  });
  socket.on("close", () => {
    rooms.get(room).delete(socket);
    if (wss.clients.size === 0) wss.close();
  });
});
const members = [["engine", "stoker"], ["engine", "clerk"], ["tower", "keeper"]];
const sockets = members.map(([room]) => new WebSocket("ws://localhost:3000/?room=" + room));
let opened = 0, got = 0;
sockets.forEach((ws, i) => {
  ws.onopen = () => { opened += 1; if (opened === 3) { sockets[0].send("pressure rising"); sockets[2].send("the clock is slow"); } };
  ws.onmessage = (event) => {
    console.log(members[i][1] + " got:", event.data);
    got += 1;
    if (got === 3) sockets.forEach((s) => s.close());
  };
});

Terminal: node app.js

stoker got: [engine] pressure rising
clerk got: [engine] pressure rising
keeper got: [tower] the clock is slow
  1. The Map of Sets is the whole of a room: a name, and who is in it. wss.clients still holds everyone, for the end.
  2. Each message went to its room's Set, so the keeper never heard about the pressure and the stoker never heard about the clock.
  3. The close listener removes the socket from its room, so a room never sends to a line that is gone.

stoker and clerk heard [engine] pressure rising; keeper heard [tower] the clock is slow.

Check: Three clients, two rooms, and each message stayed in its room.

Another way: let a client change rooms with a message { type: "join", room }, moving its socket from one Set to another.

A path that fails: keeping the room on the socket and looping over wss.clients with a filter for every message. It works for three clients and wastes time for three thousand; a Set per room sends to its members only.

When you are stuck: A client misses a broadcast, or a send fails

Was the client open when the message went? A broadcast reaches the sockets open at that moment, not later ones.

Is readyState checked? A socket that is closing is still in the Set for a moment; sending to it fails.

Is the socket removed on close? A room's Set does not empty itself; delete the socket in its close event.

Your turn

Where does the server keep every open connection, and what kind of value is it?Tap to reveal
  1. A Set, filled by ws itself.

wss.clients, a Set of the server's sockets.

Why check client.readyState === OPEN before sending in a broadcast?Tap to reveal
  1. A client may be on its way out.

A socket that is closing is still in the Set for a moment, and sending to it fails.

cat > app.js <<'END'
const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => {
  socket.send(String(wss.clients.size));
  socket.on("close", () => { if (wss.clients.size === 0) wss.close(); });
});
const sockets = [new WebSocket("ws://localhost:3000"), new WebSocket("ws://localhost:3000")];
let got = 0;
for (const ws of sockets) ws.onmessage = (event) => { console.log(event.data); if (++got === 2) sockets.forEach((s) => s.close()); };
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
1
2
  1. The first connection sees one client in the Set, the second sees two.
  2. Each client prints the size it was sent.

It prints 1, then 2.

Did you know?

Messages that wait in line

A slow listener can fill a server's memory. The ws documentation says that a socket's bufferedAmount is the number of bytes queued by send() but not yet sent to the network. A broadcast to a phone on a weak line keeps adding to it, so a server can check bufferedAmount and skip, or close, a socket that falls too far behind.

Why it fits here: It answers this topic's question: messages to a slow listener wait in memory, counted by bufferedAmount.

Sources: ws documentation; MDN: WebSocket: bufferedAmount property

Compression, off by default

WebSocket messages can be compressed. RFC 7692, of December 2015, defines the permessage-deflate extension for it. The ws package leaves it off by default on the server and on by default on the client, because it adds a significant overhead in performance and memory; its README suggests turning it on only if it is really needed.

Why it fits here: It adds to this topic's many listeners: compression saves bytes but costs memory, so ws leaves it off on servers.

Sources: RFC 7692: Compression Extensions for WebSocket; ws on GitHub

In one line

The server keeps every open socket in wss.clients. A broadcast loops over it and sends to each OPEN one, skipping the sender when that is wanted, and a Set of your own per room sends to a group alone. A socket leaves the sets in its close event.

The life of a line

At a glance

Every line ends some day. A good program knows how, and comes back when it can.

A close carries a code and a reason: 1000 means done, 1001 going away, 1005 that no code was given, and 1006 a line that broke. The call terminate drops the line at once, and ping and pong let the server find lines that died without a word. A failed handshake fires error alone, with no close. A client that loses its line comes back with a new WebSocket, after a delay that grows each time.

Take a guess: Is code 1006 ever sent down the line?

A request ends by itself; a line ends when one side closes it, or when something breaks. Both sides need to know which, and why. The close has a code, a number, and a reason, a short text, and both arrive in the other side's close event. The server here sends a last word and then closes with a code and a reason:

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => {
  socket.send("goodbye");
  socket.close(1001, "the server is going away");
});
const ws = new WebSocket("ws://localhost:3000");
ws.onmessage = (event) => console.log("client got:", event.data);
ws.onclose = (event) => { console.log("client: closed by the server with", event.code, JSON.stringify(event.reason)); wss.close(); };

Terminal: node app.js

client got: goodbye
client: closed by the server with 1001 "the server is going away"

Messages and the close travel in order, so goodbye arrived before the close. Code 1001 means going away: the server is shutting down, or the page is leaving. The reason is for people; the code is for programs, as a status and a message were for a request.

CodeNameWho sends it
1000normal closureeither side, when the work is done
1001going awaya server shutting down, or a page being left
1005no status receivednobody: what the other side reports when close was called with no code
1006abnormal closurenobody: what a side reports when the line broke without a close
1008policy violationa server refusing what a client did
1011internal errora server that failed
1012service restarta server about to come back
4000 to 4999your own codeseither side, with a meaning your program defines

Call close with no code, as the first block of the lesson did, and the other side reports 1005. Codes from 4000 to 4999 are yours to define, as the first section's 4000 was.

Ending without a handshake

close is polite: it sends a close frame and waits for the other side's. terminate is not: it drops the line at once, and the other side reports 1006, with wasClean false. It is for a client that has stopped answering, and for shutting a server down. wss.close stops the server from taking new lines but leaves the open ones alone, so a program that wants to end terminates them:

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => {
  console.log("server: a client; now", wss.clients.size);
  socket.on("close", () => console.log("server: the client left; now", wss.clients.size));
});
const ws = new WebSocket("ws://localhost:3000");
ws.onopen = () => {
  console.log("client: open");
  setTimeout(() => { wss.close(); console.log("server: wss.close() called; clients still", wss.clients.size); for (const c of wss.clients) c.terminate(); }, 20);
};
ws.onclose = (event) => console.log("client: close", event.code, "wasClean:", event.wasClean);

Terminal: node app.js

server: a client; now 1
client: open
server: wss.close() called; clients still 1
client: close 1006 wasClean: false
server: the client left; now 0

After wss.close the client was still in the Set, and the line still open; terminate ended it, the client heard 1006 and wasClean false, and the server's close event ran last, with the Set empty.

Is anyone there? ping and pong

A line that nobody has used for a while may be dead: the client's laptop went to sleep, a router dropped the connection, and neither side was told. The protocol has a question for it, ping, which every WebSocket answers by itself with a pong. The server sends it; a browser's WebSocket answers without the page knowing:

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => {
  socket.on("pong", () => console.log("server: pong came back"));
  socket.ping();
  setTimeout(() => socket.close(), 50);
});
const ws = new WebSocket("ws://localhost:3000");
ws.onclose = (event) => { console.log("client: close", event.code); wss.close(); };

Terminal: node app.js

server: pong came back
client: close 1005

A real server pings every client every thirty seconds or so, from a timer. It marks each one dead when the ping goes out and alive when its pong comes back, and terminates any client still marked dead at the next ping. The ws package's documentation calls this the heartbeat, and every long-running server has one.

A line that fails to open

The handshake can fail: no server on that port, a server with no WebSocket attached, a wrong path. The client's error event fires, with one message for every cause, and readyState stays 0. In Node 22, measured, no close event follows, and the waiting client keeps the process alive, so this program ends itself:

app.js

const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("a plain HTTP server, no WebSocket server attached"));
const server = app.listen(3000, () => {
  const ws = new WebSocket("ws://localhost:3000/live");
  ws.onerror = (event) => { console.log("error:", event.message, "| readyState:", ws.readyState); server.close(); process.exit(0); };
  ws.onclose = (event) => console.log("close:", event.code);
});

Terminal: node app.js

error: Received network error or non-101 status code. | readyState: 0

The error event's message does not say which cause it was, and in a browser the console says a little more. The cure is on the server: attach ws, match the path. On the client, the only move after a failed handshake is to try again later, which the example does.

Worked example 6

Reconnect when the line drops: a server that restarts once, closing its first client with 1012, and a client that comes back after a growing delay and stops only when it closed on purpose.

What we have: a server that closes the first connection with 1012 and welcomes the second; a connect function on the client that the close handler calls again

What we need: the client reports the 1012, reconnects after 50 ms, gets the welcome, and closes with 1000 without reconnecting

The plan: in onclose, return for 1000; otherwise schedule connect after delay and double delay; make a new WebSocket in connect each time

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
let connections = 0;
wss.on("connection", (socket) => {
  connections += 1;
  if (connections === 1) { socket.close(1012, "restarting"); return; }
  socket.send("welcome back");
  socket.on("close", () => wss.close());
});
let delay = 50;
function connect() {
  const ws = new WebSocket("ws://localhost:3000");
  ws.onmessage = (event) => { console.log("client got:", event.data); ws.close(1000, "done"); };
  ws.onclose = (event) => {
    if (event.code === 1000) { console.log("client: closed on purpose"); return; }
    console.log(`client: closed with ${event.code} ${event.reason}; reconnecting in ${delay} ms`);
    setTimeout(connect, delay);
    delay *= 2;
  };
}
connect();

Terminal: node app.js

client: closed with 1012 restarting; reconnecting in 50 ms
client got: welcome back
client: closed on purpose
  1. A WebSocket cannot be reopened: a closed one stays closed, and connect makes a new one each time.
  2. The delay doubles each time, which is called backoff: a server that is restarting is not helped by a thousand clients reconnecting at once, every 50 milliseconds.
  3. Code 1000 is the one close that means done, so the client reconnects on every other code, 1006 included.

closed with 1012 restarting; reconnecting in 50 ms, then welcome back, then closed on purpose.

Check: One restart, one reconnect, and no reconnect after the close that was meant.

Another way: cap the delay at thirty seconds, and add a little randomness to it, so that clients do not all return in step.

A path that fails: reconnecting from the error event. After a failed handshake no close event follows, so a client that reconnects only on close would wait for ever; reconnect on error too.

When you are stuck: The line ends, or never opens, and I do not know why

Read the close event's code: 1005 is a close with no code, 1006 a line that broke, 1001 a server going away.

Is the error event handled? A failed handshake fires error and nothing else; put the reconnect there as well as on close.

Did the server end the program without terminating? wss.close leaves open lines open; terminate them to end.

Your turn

The other side called close() with no code. Which code does your close event show?Tap to reveal
  1. It is the number for no status received.

1005.

What does a WebSocket do when a ping arrives, and what does the server learn from it?Tap to reveal
  1. The answer has a name of its own.

It answers with a pong by itself; a pong that comes back means the line is alive.

cat > app.js <<'END'
const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => socket.terminate());
const ws = new WebSocket("ws://localhost:3000");
ws.onclose = (event) => { console.log(event.code, event.wasClean); wss.close(); };
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
1006 false
  1. terminate drops the line without a close frame.
  2. The other side reports 1006, abnormal closure, and wasClean false.

It prints 1006 false.

Did you know?

1006 is never sent

Code 1006 never travels down the line. RFC 6455 says it is a reserved value that must not be set as a status code in a Close frame by either side. It exists for programs that need a code meaning the connection closed abnormally, without a Close frame sent or received: a line that broke, so nobody could say goodbye.

Why it fits here: It answers this topic's question: 1006 is never sent; a program reports it itself when a line breaks with no Close frame.

Source: RFC 6455: The WebSocket Protocol

Add jitter to the delay

A growing delay is not quite enough. Marc Brooker's post on the AWS Architecture Blog, of 4 March 2015, showed that exponential backoff alone still leaves clusters of calls, as clients retry at the same moments. Its answer: the solution is not to remove backoff, but to add jitter, a random part in each delay, so that the retries spread out.

Why it fits here: It sharpens this topic's reconnect: a random part in each delay spreads clients out, where doubling alone keeps them together.

Source: AWS Architecture Blog: Exponential Backoff and Jitter

In one line

A close carries a code and a reason: 1000 means done, 1001 going away, 1005 no code given, 1006 a line that broke. Terminate drops the line at once, and ping and pong keep the server honest about dead lines. A failed handshake fires error alone, and a client comes back with a new WebSocket after a growing delay.

Where it is used

A line that stays open is behind every page that changes without a reload. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
the handshake and the open lineevery live pagea dashboard whose numbers move
ws beside Expressmost Node servers with live pagesan API and its live feed on one port
JSON with a type fieldevery WebSocket programa chat's join, message and leave types
broadcast and roomschat, games, shared documentsa document edited by several people at once
close codes and reconnectevery client in the wilda page that comes back after the train's tunnel
ping and pongevery long-running servera heartbeat that drops dead connections

Many sites reach for a library above ws, such as Socket.IO, which adds rooms, reconnect and a fallback for networks that block WebSockets; what it adds is what this lesson built by hand. For one-way news from the server, Server-Sent Events, an HTTP answer that never ends, are a simpler choice, and a request is still the right shape for everything a client asks for once.

In the Couriers' Yard, the speaking tube is the line, the tap and the tap back are ping and pong, and the number a hall says when it leaves is the close code.

Mistakes and debugging

These are the mistakes that WebSocket beginners make most, each with the way to see it and the fix.

1. Sending before the line is open

new WebSocket returns at once, with the handshake still on its way:

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
const ws = new WebSocket("ws://localhost:3000");
try {
  ws.send("too soon");
} catch (e) {
  console.log(e.name + ":", e.message);
}
ws.onopen = () => ws.close();
ws.onclose = () => wss.close();

Terminal: node app.js

InvalidStateError: Sent before connected.

The send threw an InvalidStateError. Send from the open handler, or keep a queue and send it when open fires.

2. Sending an object

send takes text or bytes. An object becomes its text, which is not JSON:

app.js

const { WebSocketServer } = require("ws");
const wss = new WebSocketServer({ port: 3000 });
wss.on("connection", (socket) => socket.on("message", (data) => { console.log("server got:", JSON.stringify(data.toString())); socket.close(); }));
const ws = new WebSocket("ws://localhost:3000");
ws.onopen = () => ws.send({ type: "read", gauge: "boiler" });
ws.onclose = () => wss.close();

Terminal: node app.js

server got: "[object Object]"

The server received the string [object Object]. Call JSON.stringify before send, and JSON.parse after the message event, every time.

3. Reading a text message as if it were a string, on the server

On the server, a message is a Buffer. Comparing it with a string, data === "ping", is always false, and so is a switch on it. Call data.toString() first; JSON.parse does it for you.

4. A throw inside a message listener

A listener runs in a callback, outside any request. A throw there, such as JSON.parse on a bad message, ends the process for every client on every line, as lesson 06 showed. Parse inside try, and answer the one client with an error message.

5. Forgetting the clients that are gone

A Set of your own, for a room, does not empty itself. A socket that closed stays in it until your close listener removes it, and a send to it fails. Remove the socket in its close event, and check readyState before every send.

6. A server that cannot end

wss.close stops new handshakes and leaves open lines open; a program that calls it and waits for the process to end waits for ever. Terminate the clients, or close them with 1001, going away.

The debugging corner: watch the line

Print every event on both sides, with readyState, as the order section's block did: the order of the lines shows where a program went wrong. In a browser, the Network panel's WS tab lists every frame on a line, both ways, with its time.

For a handshake that fails, look at the server first: is ws attached, is the path right, is the port the one the client used?

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

app.js

const express = require("express");
const { WebSocketServer, WebSocket: ServerSocket } = require("ws");
const app = express();
const gauges = { boiler: 95 };
app.get("/gauges", (req, res) => res.json(gauges));
const server = app.listen(3000);
const wss = new WebSocketServer({ server, path: "/live" });
const broadcast = (message) => {
  for (const client of wss.clients) if (client.readyState === ServerSocket.OPEN) client.send(JSON.stringify(message));
};
wss.on("connection", (socket) => {
  socket.send(JSON.stringify({ type: "hello", clients: wss.clients.size }));
  socket.on("message", (data) => {
    let message;
    try { message = JSON.parse(data); } catch { return socket.send(JSON.stringify({ type: "error", message: "not JSON" })); }
    if (message.type === "set") { gauges[message.gauge] = message.value; broadcast({ type: "reading", gauge: message.gauge, value: message.value }); }
    else socket.send(JSON.stringify({ type: "error", message: `no such type: ${message.type}` }));
  });
  socket.on("close", (code) => { if (wss.clients.size === 0) { console.log("server: last client left with", code); server.close(); } });
});
const a = new WebSocket("ws://localhost:3000/live");
const b = new WebSocket("ws://localhost:3000/live");
let opened = 0;
const onopen = () => { opened += 1; if (opened === 2) a.send(JSON.stringify({ type: "set", gauge: "boiler", value: 96 })); };
a.onopen = onopen; b.onopen = onopen;
let readings = 0;
const onmessage = (who) => (event) => {
  console.log(who, "got:", event.data);
  if (JSON.parse(event.data).type === "reading" && ++readings === 2) a.close(1000, "done");
};
a.onmessage = onmessage("a"); b.onmessage = onmessage("b");
a.onclose = () => b.close(4000, "shift over");

Terminal: node app.js

a got: {"type":"hello","clients":1}
b got: {"type":"hello","clients":2}
a got: {"type":"reading","gauge":"boiler","value":96}
b got: {"type":"reading","gauge":"boiler","value":96}
server: last client left with 4000
When you seeIt meansDo
InvalidStateError: Sent before connectedsend before opensend from the open handler
[object Object] on the serveran object given to sendJSON.stringify before send
a Buffer where you wanted textthe server's message eventdata.toString(), or JSON.parse(data)
a Blob on the clienta binary messageawait data.arrayBuffer(), or binaryType = "arraybuffer"
426 Upgrade Requireda plain request to a WebSocket serverconnect with ws://, from a WebSocket
error, and no closethe handshake failedattach ws, match the path; reconnect from error too
close 1006, wasClean falsethe line broke, or was terminatedreconnect with a growing delay
close 1005close was called with no codepass a code when the reason matters
a program that never endswss.close left lines openterminate the clients, or close them with 1001

The story: The tube stays open

You lay the tube. A courier asks once, the yard agrees, and from then on the two halls talk. The gauge speaks the moment its reading changes, and the Engine Hall hears it at once. A dozen halls listen to the same tube, and one word from the yard reaches them all.

A tube that goes quiet is tested with a tap; a tap comes back, or the tube is declared dead and laid again. When a hall leaves, it says so, with a number that tells why.

The Yardmaster hangs your slip beside the others. "The yard's rules are yours now," she says. "Across the road stands the Testing House, where every yard's work is checked by hand."

Reagents gathered: WebSocket, handshake, message event, broadcast, close code, ping.

Sources