Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 ยท Projects and Practice

Project: A Signalling Server With Rooms

Design a WebSocket signalling server for WebRTC: join a room, relay offers, answers and candidates, handle leave events. Run the same protocol against an in-page hub and read the Node server.

Every WebRTC app needs a way for peers to meet and exchange offers, answers and ICE candidates before a direct connection exists. WebRTC does not define this channel; you choose it. The most common choice is a WebSocket server that groups users into rooms and relays messages between them.

In this project you will design the protocol, read a complete Node.js server (about 60 lines), and then run the same protocol against an in-page stand-in hub, so you can watch two clients join a room, negotiate a connection and exchange a message, without leaving the lesson.

Honest note: a real server needs a machine and a WebSocket library, so the Node code is read-only here. The runnable part uses a Hub class with the same message shapes, which a WebSocket would carry as JSON text.

The protocol

Keep it small. Every message is a JSON object with a type.

Direction Message Purpose
client to server { type: "join", room } Enter a room
server to client { type: "joined", id, peers: [ids] } You are in; here is who is already there
server to others { type: "peer-joined", id } A new peer arrived
client to server { type: "signal", to, data } Relay data (offer, answer or candidate) to peer to
server to client { type: "signal", from, data } Relayed message
server to others { type: "peer-left", id } A peer disconnected

The server never reads data. It only forwards it, which keeps it simple and keeps it independent of SDP details.

sequenceDiagram
  participant A as Client A
  participant S as Server
  participant B as Client B
  A->>S: join "demo"
  S-->>A: joined (peers: [])
  B->>S: join "demo"
  S-->>B: joined (peers: [A])
  S-->>A: peer-joined B
  B->>S: signal to A (offer)
  S-->>A: signal from B (offer)
  A->>S: signal to B (answer)
  S-->>B: signal from A (answer)
  Note over A,B: ICE candidates flow the same way, then media or data go direct

The newcomer makes the offer, which avoids both sides offering at once.

The Node.js server (read-only)

This uses the popular ws package. It is not runnable in this lesson, and it is intentionally minimal: a production server adds authentication, limits and logging, covered below.

JavaScript
// server.js (read-only; run with: npm install ws && node server.js)
import { WebSocketServer } from 'ws';
import { randomUUID } from 'node:crypto';

const wss = new WebSocketServer({ port: 8081, maxPayload: 64 * 1024 });
const rooms = new Map(); // roomName -> Map(id -> socket)

function send(socket, message) {
  if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(message));
}

wss.on('connection', (socket) => {
  socket.id = randomUUID();
  socket.room = null;

  socket.on('message', (raw) => {
    let msg;
    try {
      msg = JSON.parse(raw);
    } catch {
      return socket.close(1003, 'bad json');
    }

    if (msg.type === 'join' && typeof msg.room === 'string' && !socket.room) {
      const room = rooms.get(msg.room) ?? new Map();
      if (room.size >= 8) return send(socket, { type: 'error', reason: 'room full' });
      rooms.set(msg.room, room);
      send(socket, { type: 'joined', id: socket.id, peers: [...room.keys()] });
      for (const peer of room.values()) send(peer, { type: 'peer-joined', id: socket.id });
      room.set(socket.id, socket);
      socket.room = msg.room;
    } else if (msg.type === 'signal' && socket.room) {
      const target = rooms.get(socket.room)?.get(msg.to);
      if (target) send(target, { type: 'signal', from: socket.id, data: msg.data });
    }
  });

  socket.on('close', () => {
    const room = rooms.get(socket.room);
    if (!room) return;
    room.delete(socket.id);
    for (const peer of room.values()) send(peer, { type: 'peer-left', id: socket.id });
    if (room.size === 0) rooms.delete(socket.room);
  });
});
console.log('signalling on ws://localhost:8081');

The browser side connects with new WebSocket('wss://signal.example.org') and sends and receives the same messages the stand-in uses below.

Run the protocol in the page

The Hub class mirrors the server's logic. A Client object wraps a RTCPeerConnection, joins a room, and negotiates with every peer it hears about. The "socket" is a plain object with a send method and an onmessage callback, the same shape as a WebSocket.

JS Join a room and connect through a hub

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Three clients form a mesh (see Mesh, MCU and SFU): Ana connects to Ben and Cleo, and Ben to Cleo, so each has two open channels. Every one of those connections negotiated through the same hub using only join and signal messages.

Why the newcomer offers

If both peers created offers when they discover each other, the offers would collide ("glare"). Making the newcomer the offerer is the simplest fix: the server tells the newcomer about existing peers (joined) and tells existing peers about the newcomer (peer-joined), but only the newcomer reacts by calling createOffer. The established peers wait for offers. For connections that need renegotiation later, use the "perfect negotiation" pattern from the earlier chapters of this track.

Hardening the server

A teaching server trusts everyone. Before exposing yours:

  • Authenticate the WebSocket. Require a short-lived token on connect (wss://...?token= is visible in logs; prefer a first message, or a cookie with SameSite).
  • Authorise per room. Do not let anyone join any room name; check membership against your own database.
  • Validate everything. Types, string lengths, to ids, maximum payload size (maxPayload above), and rate limits per socket.
  • Never relay arbitrary fields, only the documented ones.
  • Cap room size (mesh above 4 to 6 people is not sensible anyway).
  • Use TLS (wss://) so offers and fingerprints are not tampered with on the way (Security: DTLS and SRTP).
  • Scale out with Redis pub/sub so peers of one room can sit on different servers (WebRTC in Real Apps).

Ideas to extend it

  1. Add peer-left handling in the client: close that peer's connection and remove it from the map.
  2. Add display names to join and show them in the UI.
  3. Send TURN credentials in the joined message, generated per user (TURN Servers).
  4. Reconnect the socket after a drop and rejoin the same room.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the signalling server do with the contents of a 'signal' message?

    The server is a relay; offers, answers and candidates are opaque data to it.
  2. 2. Why is the newcomer the one who creates offers?

    If one side always initiates, there is no collision of simultaneous offers.
  3. 3. How many peer connections does each person hold in a mesh room of 4?

    Each of the four peers connects to the other three.
  4. 4. Which is the most important protection for a public signalling server?

    Without authentication and limits, anyone can join rooms, spy on signalling or overload the server.

Summary

  • A signalling server is a small relay with rooms: join, joined, peer-joined, signal, peer-left.
  • It forwards offers, answers and candidates without understanding them.
  • The newcomer offers to avoid glare; established peers answer.
  • Authenticate, authorise, validate and limit, and use wss://.

Next: Practice: WebRTC Exercises