A First WebSocket Connection

The ws package puts a WebSocketServer on the same server and port as an Express app, its connection, message and close events let the server hear from each client and answer it, and the browser's own WebSocket connects a page, with JSON messages whose type says what each one is.

Journeyman · Node.js · Web Development · Updated

By

After this lesson you can

  • Start a ws WebSocketServer on the same server as an Express app, and handle its connection, message and close events
  • Connect a page with the browser's WebSocket, sending with send and reading each message in a message listener
  • Send and read JSON messages with a type, answering an unknown type or text that isn't JSON with an error message

Key takeaways

  • new WebSocketServer({ server }) puts a WebSocket line on the same server and port as an Express app made with http.createServer(app).
  • The connection event gives you each client's socket. socket.send sends that client a message, and its message and close events hear from it.
  • In the browser, new WebSocket("ws://localhost:3100") opens the line. Its open event says it's ready to send, and its message event brings each message.
  • A message is only text, so send JSON with a type field, such as a cheer for the hawks, and let the type decide what happens.
  • Text that isn't JSON, or a type the server doesn't know, gets an error message back, because an error thrown in a message listener stops the whole server.

Live features are nearly always added to an API that already exists: a chat box beside a shop's orders, a notification on top of a sign-in. So the first job is to give an Express app a WebSocket line without taking anything away from it. You'll do exactly this the first time a project asks for anything live.

Hilltop's scoreboard page is getting a cheer button: fans tap it to cheer for their team, and the server counts every cheer. The site is already an Express app. This lesson adds a WebSocket line to it, on the same port, and connects the page.

The ws package, beside Express

Node's built-in modules have no WebSocket server, so Node projects use a package for it, and ws is the one most of them use. In a folder of its own, with a package.json holding { "type": "module" }, install it with Express:

npm install express@5.3.0 ws@8.23.0

app.listen makes a server for you behind the scenes. To share one with ws, make it yourself with http.createServer(app), as the earlier chapters' server.js did, then hand it to new WebSocketServer({ server }). Ordinary requests still go to Express; a request that asks to upgrade goes to ws. One server, one port, two kinds of conversation. Here's server.js:

import http from "node:http";
import express from "express";
import { WebSocketServer } from "ws";

const app = express();
app.use(express.static("public"));

const server = http.createServer(app);
const wss = new WebSocketServer({ server });

wss.on("connection", (socket) => {
  console.log("A fan connected");
  socket.send("Welcome to the Hilltop Intramurals scoreboard!");

  socket.on("message", (data) => {
    console.log("The page sent:", data.toString());
    socket.send("Got it, thanks!");
  });

  socket.on("close", () => {
    console.log("A fan left");
  });
});

server.listen(3100, () => {
  console.log("Listening on http://localhost:3100");
});

The server's three events

The server and each line send events, and on(name, listener) runs your function each time one happens, as addEventListener does in the browser:

  • connection, on the server: a client connected. ws hands you socket, the server's end of that one client's line. Each client gets its own.
  • message, on the socket: that client sent something. It arrives as a Buffer (raw bytes), and data.toString() turns it into text.
  • close, on the socket: that client left. They closed the tab, or their phone lost its signal.

socket.send(text) sends a message to that one client, whenever you like: here, at once to greet them, and again after each message they send.

The page: the browser's own WebSocket

The browser has WebSocket built in, with no package needed. express.static("public") serves this page, public/index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Hilltop Cheers</title>
</head>
<body>
  <h1>Hilltop Intramurals</h1>
  <p>Open the developer tools' Console to see the messages.</p>
  <script>
    const socket = new WebSocket(`ws://${location.host}`);

    socket.addEventListener("open", () => {
      socket.send("Hello from the scoreboard page");
    });

    socket.addEventListener("message", (event) => {
      console.log(event.data);
    });
  </script>
</body>
</html>

location.host is the page's own host and port, localhost:3100, so the page connects back to the server that sent it. A line can't send until it's open, so the first message waits for the open event; each message that arrives is in event.data. Start the server with node server.js, open http://localhost:3100, then close the tab. The terminal shows:

Listening on http://localhost:3100
A fan connected
The page sent: Hello from the scoreboard page
A fan left

The Console shows the server's two messages:

Welcome to the Hilltop Intramurals scoreboard!
Got it, thanks!

The browser's developer tools on the Hilltop Cheers page, with the Network tab filtered to WS and the connection selected: its Messages list shows three messages, the server's welcome, the page's hello and the server's thanks

Messages as JSON with a type

A message is only text. As soon as there's more than one kind, such as a cheer, a chat line and a score, the server has to tell them apart. The usual answer: every message is JSON with a type, such as { "type": "cheer", "team": "hawks" }, and the type decides what happens. The server's messages carry a type too, so the page can tell the count from an error.

Keep that decision in a function of its own, so you can run and test it without a server. reply takes the cheer counts and a message's text, and returns the answer:

function reply(cheers, text) {
  let message;
  try {
    message = JSON.parse(text);
  } catch {
    return { type: "error", message: "Messages must be JSON." };
  }

  switch (message.type) {
    case "cheer":
      cheers[message.team] += 1;
      return { type: "cheers", hawks: cheers.hawks, foxes: cheers.foxes };
    default:
      return { type: "error", message: `Unknown message type: ${message.type}.` };
  }
}

const cheers = { hawks: 0, foxes: 0 };

console.log(reply(cheers, '{"type":"cheer","team":"hawks"}'));
console.log(reply(cheers, '{"type":"cheer","team":"hawks"}'));
console.log(reply(cheers, '{"type":"boo","team":"foxes"}'));
console.log(reply(cheers, "Go Hawks!"));
{ type: 'cheers', hawks: 1, foxes: 0 }
{ type: 'cheers', hawks: 2, foxes: 0 }
{ type: 'error', message: 'Unknown message type: boo.' }
{ type: 'error', message: 'Messages must be JSON.' }

The try matters more than it looks. An error thrown inside a message listener stops the whole server, and every fan's line with it: one fan typing Go Hawks! would end the game for everyone with SyntaxError: Unexpected token 'G', "Go Hawks!" is not valid JSON. So bad text gets an error message back instead. In server.js, keep a cheers object beside wss, and the message listener sends what reply returns:

  socket.on("message", (data) => {
    const answer = reply(cheers, data.toString());
    socket.send(JSON.stringify(answer));
  });

On the page, a cheer button sends JSON, and the message listener reads it with JSON.parse and checks its type:

cheerButton.addEventListener("click", () => {
  socket.send(JSON.stringify({ type: "cheer", team: "hawks" }));
});

socket.addEventListener("message", (event) => {
  const message = JSON.parse(event.data);
  if (message.type === "cheers") {
    hawksCount.textContent = message.hawks;
  }
});

For now, only the fan who tapped sees the new count. Broadcasting and Rooms sends it to everyone.

Check yourself

2 questions to try on the lesson page.

So what

A ws server beside Express, the browser's own WebSocket, and JSON with a type: that's the whole kit for a live feature, and everything else in this chapter is deciding who gets each message.

Key terms

Related