Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 36 ยท Concepts and Signalling

Signalling Channels

Design a WebRTC signalling channel: what messages to send, how to use WebSockets and rooms, queue early ICE candidates, and handle joins, leaves and errors.

WebRTC moves media between peers, but it cannot help two strangers find each other. Before the handshake can start, something must carry the offer, the answer and the ICE candidates from one browser to the other. That something is the signalling channel, and the standard deliberately leaves it to you.

You can use anything that delivers messages: a WebSocket server, Server-Sent Events plus HTTP POST, a managed realtime service, a message queue, a chat app, or two people pasting text into each other's browsers. WebRTC does not care. In this lesson you build a small but realistic signalling layer, learn the message design that works, and meet the one classic bug: ICE candidates that arrive before the description they belong to.

What runs here. The preview cannot open a WebSocket to a server we control, so the live examples use a stand-in server object that runs in the page and delivers messages with a small delay, just like a network would. The real WebSocket server code is shown read-only. Everything between your peer connections and send() is identical in both cases.

What has to be sent

Only three kinds of information cross the signalling channel:

  1. Descriptions: the offer and the answer ({ type, sdp }).
  2. ICE candidates: one message per candidate (when you use trickle ICE).
  3. Application messages: who joined, who left, "I hung up", "busy", chat text, and so on.

A simple, extensible message envelope:

JSON
{ "type": "description", "to": "bob", "from": "alice", "description": { "type": "offer", "sdp": "v=0..." } }
{ "type": "candidate",   "to": "bob", "from": "alice", "candidate": { "candidate": "candidate:1 1 udp ...", "sdpMid": "0", "sdpMLineIndex": 0 } }
{ "type": "hangup",      "to": "bob", "from": "alice" }

Always include from and to (or a room id): a server with many users must know where to forward each message.

A server in about twenty lines

This Node.js server (using the popular ws package) manages rooms and forwards messages. It is read-only here because the site cannot run a socket server.

JavaScript
// server.js  (read-only example, needs: npm i ws)
import { WebSocketServer } from 'ws';

const rooms = new Map();                        // roomId -> Map(peerId -> socket)
const wss = new WebSocketServer({ port: 8081 });

wss.on('connection', (socket) => {
  let roomId, peerId;
  socket.on('message', (raw) => {
    const msg = JSON.parse(raw);
    if (msg.type === 'join') {
      ({ room: roomId, id: peerId } = msg);
      const room = rooms.get(roomId) ?? new Map();
      rooms.set(roomId, room);
      for (const other of room.values()) {
        other.send(JSON.stringify({ type: 'peer-joined', id: peerId }));
      }
      room.set(peerId, socket);
      socket.send(JSON.stringify({ type: 'joined', peers: [...room.keys()].filter(p => p !== peerId) }));
    } else {
      rooms.get(roomId)?.get(msg.to)?.send(JSON.stringify({ ...msg, from: peerId }));
    }
  });
  socket.on('close', () => {
    const room = rooms.get(roomId);
    room?.delete(peerId);
    for (const other of room?.values() ?? []) {
      other.send(JSON.stringify({ type: 'peer-left', id: peerId }));
    }
  });
});

Notice what it does not do: it never parses SDP or candidates. A signalling server is a dumb forwarder with a room list. Overwriting from on the server (instead of trusting the client) prevents users from impersonating each other.

The browser side:

JavaScript
const socket = new WebSocket('wss://example.com/signal');   // wss:// in production
socket.onopen = () => socket.send(JSON.stringify({ type: 'join', room: 'demo', id: myId }));
socket.onmessage = (e) => handle(JSON.parse(e.data));
const send = (msg) => socket.send(JSON.stringify(msg));

Running the same logic in a page

The stand-in below mimics the server. It has the same API as a socket (send, onmessage) and adds a random delay so messages can overtake each other, just like on a real network.

A stand-in signalling server

This code has a race. Because messages travel with random delay, a candidate can reach Bob before the offer it belongs to. Calling addIceCandidate without a remote description rejects with InvalidStateError, and the candidate is lost. Run the example a few times: depending on the timing you may see the error line, and sometimes the data channel never opens at all. The fix is a queue.

Queue early candidates

Keep candidates in an array until the remote description has been applied, then flush:

Fixing the race with a candidate queue

Bob's log shows candidates were queued and then flushed once the offer arrived, and the data channel opens. In a real server, ordering within one WebSocket is preserved, so the race is rarer, but it is still possible with two different channels (for example candidates by HTTP POST and descriptions by WebSocket) and the queue costs nothing.

Design checklist for real signalling

  • Authenticate users before forwarding (a token in the WebSocket URL or the first message). Never let anonymous clients message arbitrary users.
  • Use wss://. Signalling carries the DTLS fingerprint; whoever can alter the channel can attempt a man-in-the-middle.
  • Handle disconnects: send peer-left and clean up peer connections on both sides.
  • Heartbeat with ping/pong so dead sockets are noticed.
  • Reconnect the WebSocket with back-off; a signalling drop does not have to end an established call, because media flows peer to peer.
  • Limit size and rate of messages: an SDP is only a few kilobytes.
  • Scale out with a shared bus (Redis pub/sub) if several server processes hold users in the same room.

No server at all?

For demos and some tools, copy-and-paste signalling works: wait for gathering to complete, show JSON.stringify(pc.localDescription) as text, and have the other user paste it into their page (see your first loopback call). It needs two messages and no server, but it is clumsy for real users. In-tab testing can also use BroadcastChannel, and two windows of the same site can talk that way.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these does the signalling channel carry?

    Signalling carries the information needed to set up the connection. Media and data go peer to peer afterwards.
  2. 2. Why should a server overwrite the from field instead of trusting the client?

    A client could claim to be any user. The server knows which socket sent the message.
  3. 3. What goes wrong if a candidate arrives before the remote description is set?

    addIceCandidate needs a remote description. Queue early candidates and add them after setRemoteDescription.
  4. 4. Is it a problem if the signalling WebSocket drops in the middle of an established call?

    Established calls keep flowing peer to peer. You can reconnect signalling in the background.

Summary

  • Signalling is any channel that delivers descriptions, candidates and app messages; WebRTC does not define it.
  • A signalling server is a simple forwarder with rooms; use wss://, authentication and server-set sender ids.
  • Candidates can arrive before the description: queue them until setRemoteDescription has run.
  • Signalling may drop without ending a call, but you need it for renegotiation and new peers.

Next: Perfect Negotiation