Level Discoverystart here Intermediatethe architecture Expertin depth
Expert · Batch 3 · Tundra
Chapter 3 · expert level

Network protocol & state consistency

The wire-level contract: a tiny message schema, an authoritative model, compact snapshots, deliberate information asymmetry, server-side validation against cheating, and the gnarly edge cases of people joining and leaving.

1The message schema

The protocol is JSON over a WebSocket, with a single discriminator field t (type). The server server/index.js is just a router: it decodes t and delegates to the room.

server/index.js — one dispatch per message type
switch (msg.t) {
  case 'host':  /* the TV creates a room, receives a code */ break;
  case 'join':  /* a device joins by code */        break;
  case 'aim':   if (socket.room) socket.room.handleAim(socket, msg.angle, msg.power); break;
  case 'ready': if (socket.room) socket.room.handleReady(socket, msg.value !== false); break;
  case 'leave': if (socket.room) socket.room.leave(socket); break;
}

Two families: upstream messages (host, join, aim, ready, shell, config, leave…) and the server's downstream messages (hosted, joined, roster, snapshot, promote, queue…). One type, one intent, one clear route.

For the curious. A snapshot carries the continuous state; an events array piggybacks one-shot moments (fire, hit, impact, destroyed). Splitting state (where everything is) from events (what just happened) is a common netcode pattern: state can be re-sent or missed harmlessly, while events are the transient cues you fire exactly once.

2Authoritative model & intent validation

“Authoritative” doesn't mean “naive”. The server never takes a client at its word: it validates every intent before applying it. An intent only takes effect if the sender is allowed and the value is plausible.

server/Room.js — only a seated player acts, and only on its own simulation
handleAim(socket, angle, power) {
  const i = socket.slot;
  if (socket.role === 'player' && this.sim) this.sim.setAim(i, angle, power);
}

The match configuration is locked down even harder: only the player designated as configOwnerSlot (the first player, then the loser) can change it, and each field is filtered by type and by range.

server/Room.js — strict validation of the settings
if (socket.role === 'player' && socket.slot === this.configOwnerSlot) {
  if (Number.isFinite(cfg.rounds)) this.config.rounds = cfg.rounds;
  if (BIOMES.some((b) => b.id === cfg.biomeId)) this.config.biomeId = cfg.biomeId;
  if (cfg.hp === 1 || cfg.hp === 2 || cfg.hp === 3) this.config.hp = cfg.hp;
}

Even checked-out intents are clamped where it matters: the simulation forces angle and power into their legal ranges and gates on the phase, so a hacked controller asking for a 999° shot simply can't get one.

src/sim/Simulation.js — clamp & gate every intent
setAim(player, angle, power) {
  if (this.phase !== PHASE.AIMING) return;       // only while aiming
  const tower = this.towers[player];
  if (!tower || tower.ready) return;             // not after you've committed
  if (Number.isFinite(angle))
    tower.angle = Math.max(AIM.minAngle, Math.min(AIM.maxAngle, angle)); // clamp into AIM.min/maxAngle
  if (Number.isFinite(power))
    tower.power = Math.max(AIM.minPower, Math.min(AIM.maxPower, power));
}
Anti-cheat. A tampered client can send whatever it wants; it can't make happen whatever it wants. Since the physics runs on the server and intents are filtered, the worst a cheater gets is… their own message being ignored.

3Compact snapshot vs delta, and information asymmetry

At 30 Hz, the snapshot's size matters. The choice here is the full compact state rather than deltas: the heavy fields are already absent (terrain = a seed), coordinates are rounded, and only live projectiles are included.

src/sim/Simulation.js — the full snapshot, kept tiny
snapshot() {
  return {
    phase: this.phase,
    round: { current: this.currentRound, total: this.totalRounds },
    wind: this.wind,
    scores: this.scores.slice(),
    seed: this.seed,            // terrain is a function of the seed
    craters: this.craters,      // only the diffs, not every height
    towers: /* ready, groundY, angle, power, hp */,
    projectiles: this.projectiles
      .filter((p) => p.alive)
      .map((p) => ({ id: p.id, x: Math.round(p.x), y: Math.round(p.y), owner: p.owner })),
  };
}

The subtlest part is what is not in the snapshot. The angle and power chosen while aiming aren't there for the TV: the simulation exposes the “ready” flags and, once a shot is fired, the projectiles — never the secret settings.

src/sim/Simulation.js — hidden information is a protocol decision
// angle/power are deliberately omitted so the spectator TV never
// reveals what the players are setting; only the ready flags and,
// once fired, the projectiles are shared.
Compact rather than delta. A delta saves bytes but forces the server to remember what each client already knows, and complicates reconnects. Here the state is already so lean (seed + crater list + a few objects) that a full snapshot stays small and trivially idempotent: a client joining mid-game is up to date from the very first message.

4Edge cases: where the real bugs live

The happy path is “two players play then replay”. The rest are the transitions. The room covers them explicitly. Mid-match takeover: if a seat frees up, the front of the queue is promoted into it.

server/Room.js — promote the front of the queue
promoteInto(slot) {
  const next = this.waiting.shift();
  if (!next) return;
  this.players[slot] = { socket: next.socket, name: next.name, playAgain: this.postmatch };
  this.send(next.socket, { t: 'promote', player: slot, name: next.name });
}

Disconnect: removeSocket removes the socket from everywhere (TV, queue, seat), attempts a promotion, and otherwise brings the room back to the lobby. Voluntary leave: the leaver drops to the back of the queue and receives a demoted message. Lobby reset: as soon as a match loses one of its two players, the simulation is cancelled and the TV shows the code and QR again.

server/Room.js — an empty seat mid-match ⇒ back to the lobby
if (this.sim && !this.bothFilled()) this.resetToLobby();
Invariant. The room cleans itself up: as soon as it has no TV, no player and no queue, dispose() stops the loop and removes it from the rooms table. No setInterval leak, no zombie room.

5Bandwidth economy

All these decisions converge on a single goal: send as little as possible, as often as possible. The terrain — potentially thousands of heights — boils down to one seed.

src/sim/Simulation.js — the seed carries all the relief
seed: this.seed,        // one integer → thousands of regenerated heights
craters: this.craters,  // the list of holes (small circles)

Sending the seed rather than the terrain trades bandwidth for a bit of client CPU (each one regenerates the same relief). Coupled with rounded positions, the filtering of dead projectiles and the absence of assets, the 30 Hz stream stays light even over a home Wi-Fi.

Remember. A good real-time protocol isn't just about speed: it's a balance of authority, message size, revealed information and robustness to transitions. Tower Duel chooses simplicity wherever the state already allows it.
← Chapter 2 · Asset-free rendering Chapter 4 · Destructible terrain & fast maths →