TExcelTAD
Home › Multiplayer Game Networking › WebSocket, WebRTC & Colyseus

WebSocket, WebRTC & Colyseus

A browser game can't open a UDP socket. Web pages get three transports instead: WebSocket (a message channel over TCP), WebRTC data channels (which can be unordered and unreliable, like UDP) and the newer WebTransport (QUIC/HTTP/3 with datagrams). On top of them, frameworks such as Colyseus give you rooms, state sync and matchmaking for JavaScript and TypeScript servers. The general protocols are covered in the Computer Networking course; here we look at what each choice means for a real-time game.

WebSocket: easy, reliable, ordered

WebSocket is supported everywhere, passes through proxies on port 443, and is trivial to use. Send binary, not JSON, for game traffic (see Serialization & Bit-Packing):

js
const ws = new WebSocket('wss://game.example.com/play');
ws.binaryType = 'arraybuffer';                 // receive ArrayBuffer instead of Blob

ws.addEventListener('open', () => {
  const msg = new DataView(new ArrayBuffer(5));
  msg.setUint8(0, 1);                          // message type 1 = input
  msg.setUint16(1, inputSeq++);                // sequence number
  msg.setInt8(3, moveX); msg.setInt8(4, moveY);
  ws.send(msg.buffer);
});
ws.addEventListener('message', (e) => applySnapshot(new DataView(e.data)));
ws.addEventListener('close', (e) => scheduleReconnect(e.code));

The catch is TCP: every message arrives, in order. When one packet is lost, everything behind it waits for the retransmission (head-of-line blocking), so one loss turns into a burst of late snapshots. For turn-based, card, casual and many co-op games that's fine. For fast shooters at 2% loss it shows.

WebRTC data channels: UDP-like delivery

A WebRTC data channel runs over SCTP on DTLS on UDP, and you choose the delivery guarantees per channel:

js
const pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.example.com:3478' }] });

// Snapshots and inputs: unordered, never retransmitted. A lost packet is simply gone.
const fast = pc.createDataChannel('state', { ordered: false, maxRetransmits: 0 });
// Chat, purchases, round results: reliable and ordered (the default).
const reliable = pc.createDataChannel('events');

fast.binaryType = 'arraybuffer';
fast.onmessage = (e) => applySnapshot(new DataView(e.data));

maxRetransmits and maxPacketLifeTime are alternatives (setting both throws). The price is setup: peers exchange an offer and answer (SDP) and ICE candidates through a signalling server you provide (usually a WebSocket), may need a TURN relay when NAT traversal fails, and a game server needs a WebRTC stack too (libraries such as node-datachannel, or frameworks like geckos.io built for client-server WebRTC games).

WebTransport gives client-server unreliable datagrams and multiple streams over HTTP/3 with a simpler setup than WebRTC. Check current browser and server support before depending on it.

Head-of-line blocking, measured

The model sends 20 snapshots, one every 50 ms, with 60 ms one-way latency and a seeded 10% loss. On an ordered reliable channel a lost packet is resent after one round trip (120 ms) and everything behind it waits; on an unordered unreliable channel a lost snapshot is skipped and the next one is applied when it arrives.

ts · try it yourself
function mulberry32(seed: number) {
  return () => {
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

const SEND_EVERY = 50, LATENCY = 60, RTT = 2 * LATENCY, LOSS = 0.1, COUNT = 20;
const rnd = mulberry32(15);
const lost = Array.from({ length: COUNT }, () => rnd() < LOSS);
console.log('lost snapshots:', lost.map((l, i) => (l ? i : -1)).filter((i) => i >= 0).join(', '));

// Ordered + reliable (WebSocket/TCP-like): retransmit after an RTT, deliver strictly in order.
let release = 0;
const tcpDelay: number[] = [];
for (let i = 0; i < COUNT; i++) {
  const sent = i * SEND_EVERY;
  const arrives = sent + LATENCY + (lost[i] ? RTT : 0);
  release = Math.max(release, arrives);            // can't be handed to the game before earlier ones
  tcpDelay.push(release - sent);
}
// Unordered + unreliable (data channel with maxRetransmits: 0): lost ones never arrive.
const udpDelay: (number | null)[] = lost.map((l) => (l ? null : LATENCY));

const stats = (xs: number[]) => `avg ${(xs.reduce((a, b) => a + b, 0) / xs.length).toFixed(1)} ms, worst ${Math.max(...xs)} ms`;
console.log('ordered reliable  :', stats(tcpDelay), `| delivered ${COUNT}/${COUNT}`);
const got = udpDelay.filter((d): d is number => d !== null);
console.log('unordered no-retx :', stats(got), `| delivered ${got.length}/${COUNT}`);
console.log('per snapshot (ms) :', tcpDelay.map((d) => String(d).padStart(4)).join(""));
lost snapshots: 8, 12, 16
ordered reliable  : avg 91.5 ms, worst 180 ms | delivered 20/20
unordered no-retx : avg 60.0 ms, worst 60 ms | delivered 17/20
per snapshot (ms) :   60  60  60  60  60  60  60  60 180 130  80  60 180 130  80  60 180 130  80  60

The reliable channel delivers everything, but each loss delays the next couple of snapshots too. The unreliable channel loses a few snapshots and keeps the rest exactly on time, and Snapshot Interpolation hides the gaps. That is why fast games want unreliable delivery for state and reliable delivery only for events.

Colyseus: rooms and synced state for TypeScript servers

Colyseus is an open-source Node.js framework for authoritative room-based games. The docs describe version 0.18 at the time of writing; the API below follows it, but check the version you install. A server defines its state with @colyseus/schema and a Room class:

ts
// server: MyRoom.ts
import { Room, Client } from "colyseus";
import { Schema, MapSchema, type } from "@colyseus/schema";

export class Player extends Schema {
  @type("number") x = 0;
  @type("number") y = 0;
  @type("number") hp = 100;
}
export class ArenaState extends Schema {
  @type({ map: Player }) players = new MapSchema<Player>();
}

export class ArenaRoom extends Room {
  maxClients = 4;
  state = new ArenaState();

  onCreate(options: any) {
    this.onMessage("input", (client, input: { dx: number; dy: number }) => {
      const p = this.state.players.get(client.sessionId);
      if (!p) return;
      p.x += Math.max(-1, Math.min(1, input.dx)) * 4;     // validate on the server
      p.y += Math.max(-1, Math.min(1, input.dy)) * 4;
    });
    this.setTimestep((dt) => this.update(dt));             // fixed simulation step
  }
  onJoin(client: Client) { this.state.players.set(client.sessionId, new Player()); }
  onDrop(client: Client) { this.allowReconnection(client, 20); }   // hold the seat for 20 s
  onLeave(client: Client) { this.state.players.delete(client.sessionId); }
  update(dt: number) { /* projectiles, timers */ }
}

The client SDK joins a room and listens to state changes:

ts
// client
import { Client, Callbacks } from "@colyseus/sdk";

const client = new Client("https://game.example.com");
const room = await client.joinOrCreate("arena");
const callbacks = Callbacks.get(room);

callbacks.onAdd("players", (player, sessionId) => {
  addSprite(sessionId);
  callbacks.listen(player, "hp", (hp, previous) => showDamage(sessionId, previous - hp));
});
callbacks.onRemove("players", (_player, sessionId) => removeSprite(sessionId));

setInterval(() => room.send("input", readInput()), 50);

The server tracks which fields changed and, every patchRate milliseconds, sends only those fields in a compact binary patch. Clients get the full state when they join and patches afterwards. Older tutorials use colyseus.js and different callback helpers; follow the docs for your version.

A model of schema patches

The idea behind Colyseus's schema (and NGO's NetworkVariables, and Unreal's property replication) is change tracking: setters record which fields changed, and the encoder walks only that list.

ts · try it yourself
class Tracked {
  private changes = new Map<string, number>();     // field -> latest value this patch
  private data: Record<string, number> = {};
  constructor(readonly id: number, init: Record<string, number>) { this.data = { ...init }; }
  set(field: string, v: number) {
    if (this.data[field] === v) return;            // same value: no change recorded
    this.data[field] = v;
    this.changes.set(field, v);
  }
  takeChanges(): [string, number][] { const c = [...this.changes]; this.changes.clear(); return c; }
}

const fields = ['x', 'y', 'hp'];
const players = [new Tracked(1, { x: 0, y: 0, hp: 100 }), new Tracked(2, { x: 50, y: 0, hp: 100 })];

function patch(label: string) {
  const ops: string[] = [];
  let bytes = 0;
  for (const p of players) {
    const ch = p.takeChanges();
    if (ch.length === 0) continue;
    bytes += 1 + ch.length * 3;                    // ref id + (field index byte + 2-byte value) per change
    ops.push(`#${p.id} ${ch.map(([f, v]) => `${f}(${fields.indexOf(f)})=${v}`).join(' ')}`);
  }
  console.log(`${label.padEnd(24)} ${String(bytes).padStart(2)} bytes  ${ops.join(' | ') || '(empty patch, not sent)'}`);
}

players[0].set('x', 4); players[0].set('x', 8); players[0].set('x', 12);
patch('p1 moved three times');
players[1].set('hp', 75); players[0].set('y', 4);
patch('p2 hit, p1 moved up');
players[0].set('hp', 100);
patch('p1 hp set to same value');
p1 moved three times      4 bytes  #1 x(0)=12
p2 hit, p1 moved up       8 bytes  #1 y(1)=4 | #2 hp(2)=75
p1 hp set to same value   0 bytes  (empty patch, not sent)

Three moves in one patch interval cost one field; untouched players cost nothing; and a write of the same value isn't sent at all. A JSON snapshot of both players would be about 70 bytes every time.

Test yourself

Why does a single lost packet hurt a WebSocket game more than a game using an unreliable data channel?

  1. WebSocket messages are larger
  2. TCP delivers in order, so everything behind the lost packet waits for its retransmission
  3. WebSocket can't send binary
  4. Data channels compress data

Which options create a WebRTC data channel that behaves like UDP?

  1. { ordered: true }
  2. { ordered: false, maxRetransmits: 0 }
  3. { negotiated: true }
  4. { maxRetransmits: 0, maxPacketLifeTime: 0 }

In Colyseus, what reaches clients when the server changes player.x three times within one patch interval?

  1. Three messages
  2. One patch containing the latest value of x
  3. The whole state
  4. Nothing until the client asks