Exercise: Live Match Scoreboard

Write the live line behind Hilltop Intramurals' scoreboard with the ws package, so every goal reaches every open page at once, a fan who connects late sees the score straight away, bad messages get an error back, and everyone sees how many are watching, with real WebSocket clients in the tests.

Journeyman · Node.js · Web Development · Updated

By

Hilltop Intramurals plays its soccer games on Field 1, and the fans who can't be there keep texting each other "What's the score?" The pages are ready: a viewer's page that shows the score and how many people are watching, and a scorekeeper's page with a button for each team's goals. You'll write the live line behind them with the ws package, so a goal shows on every open phone the moment it's scored. Tests connect real WebSocket clients and check every message.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-node-live-match-scoreboard, also linked from the Exercise box beside the lesson. Clone it into your nodejs-course folder. In VS Code's terminal:

cd ~/nodejs-course
git clone https://github.com/ask-codey/exercise-node-live-match-scoreboard.git

Git makes a folder, exercise-node-live-match-scoreboard, with the exercise code inside. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and install its two packages, Express and ws:

npm install

Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder.

The folder holds:

  • scoreboard.js: attachScoreboard(server), which starts a WebSocketServer on the server it's given, for you to finish.
  • app.js: the Express app that serves the pages.
  • server.js: starts the pages and the live line together at http://localhost:3100, on one server and one port.
  • public/: the viewer's page, the scorekeeper's page and their browser code, live.js. You don't need to change them.
  • scoreboard.test.js: the tests, which connect WebSocket clients to a fresh scoreboard for every test. You don't need to change it.

What to do

scoreboard.js already starts the WebSocketServer. For now, it tells every client that connects { "type": "error", "message": "Not built yet." }. The comment at its top lists every message it should send, and to whom:

// When a client connects:
//   to that client:          { "type": "score", "hawks": 0, "foxes": 0 }   the score right now, at once
//   to every open client:    { "type": "viewers", "count": 1 }             how many are connected, the newcomer included
//
// When a client sends:
//   { "type": "goal", "team": "hawks" }   to every open client: { "type": "score", "hawks": 1, "foxes": 0 }
//   { "type": "goal", "team": "foxes" }   the same, with one more goal for the foxes
//   { "type": "goal", "team": "eagles" }  to the sender only: { "type": "error", "message": "There's no team eagles." }
//                                         (any team that isn't hawks or foxes, named as it was sent; the score stays)
//   { "type": "cheer" }                   to the sender only: { "type": "error", "message": "Unknown message type: cheer." }
//                                         (any other type, named as it was sent)
//   Go Hawks!                             to the sender only: { "type": "error", "message": "Messages must be JSON." }
//                                         (anything that isn't JSON)
//
// When a client leaves:
//   to every client still open:  { "type": "viewers", "count": 1 }   the new count, without the one who left
  1. Keep the score inside attachScoreboard, starting at 0 to 0, so every test starts fresh.
  2. Greet each client that connects with the score, then tell every open client the new count of viewers.
  3. Read each message as JSON, and answer text that isn't JSON with its error, to the sender only.
  4. Count a goal for the hawks or the foxes and send the new score to every open client. Answer any other team, or any other type, with its error, to the sender only.
  5. When a client leaves, tell every client still open the new count.

Check your work

Run the tests from the exercise folder:

npm test

No server needs to be running: each test starts its own scoreboard on a port the computer picks, connects its clients, and closes them all afterwards. At first all 10 tests fail, each after waiting a second for a message that never comes. That's expected: each message you send turns tests green. A failing test's message says who should have got what, and what did come, for example Maya, on connecting, should get a score message, but none came within 1 second. What came: {"type":"error","message":"Not built yet."}.

To see it yourself, start it with npm start (or npm run dev, which restarts it each time you save). Open http://localhost:3100 in your browser, and http://localhost:3100/scorekeeper.html in a second window beside it. Click a goal button and watch both pages. Stop it with Ctrl+C.

Hints

  • Start with the moment a client connects. Send the newcomer the score, then everyone the count, and tests 1 to 3 turn green. A First WebSocket Connection shows the connection event and socket.send.
  • One function for "everyone". A broadcast function that loops over wss.clients and sends to each client whose readyState is WebSocket.OPEN, as in Broadcasting and Rooms, does the score, the count and the goals.
  • A message arrives as a Buffer, and JSON.parse can throw. data.toString() gives its text. Catch the error, or one fan typing Go Hawks! stops the scoreboard for everyone.
  • Check the type, then the team. Adding 1 to a team that isn't in the score doesn't stop the server, but it quietly fills the score with nonsense.
  • A client that closed is already out of wss.clients when its close event runs, so wss.clients.size is the new count.

When you're done

Every test is green. With npm start running, a viewer that connects and stays while a scorekeeper connects, scores one goal for each team and leaves gets these messages, in this order (the browser's developer tools show them on the Network tab, filtered to WS):

{"type":"score","hawks":0,"foxes":0}
{"type":"viewers","count":1}
{"type":"viewers","count":2}
{"type":"score","hawks":1,"foxes":0}
{"type":"score","hawks":1,"foxes":1}
{"type":"viewers","count":1}

Now look back at scoreboard.js. If Hilltop added Field 2 next Saturday, with its own game and its own fans, which parts would turn into a room, and what would each room have to keep?

Submit your exercise

The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.

  1. On GitHub, click +, then New repository. Name it (for example exercise-node-live-match-scoreboard), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:

    git remote set-url origin https://github.com/your-name/exercise-node-live-match-scoreboard.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-node-live-match-scoreboard, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.

Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

A live feature is a handful of rules about who hears what, and when: the newcomer, everyone, or only the sender. You've written all three, tested them with real clients, and that's the core of every scoreboard, chat and notification you'll build.

Key terms

Related