Building a Peer-to-Peer Signaling Server
In this lesson, you will learn how to use WebSockets to act as an intermediary, facilitating the exchange of SDP (Session Description Protocol) tokens to establish a direct WebRTC peer-to-peer connection.
The Role of the Signaling Server
WebRTC enables browsers to communicate directly, but they cannot "find" each other on the internet without help. Before a peer-to-peer data channel can open, two clients must agree on how to talk (codecs, security, and network paths). This metadata is packaged as an SDP Offer and an SDP Answer.
Because neither client has the other’s address yet, they use your Node.js WebSocket server as a "middleman" to swap these tokens. Your server doesn’t handle the actual audio, video, or data traffic; it only routes these text-based "handshake" messages between peers.
Orchestrating the Exchange
The flow follows a simple request-relay pattern. When Peer A wants to connect to Peer B, it sends an offer through the socket. Your server identifies Peer B and forwards that exact payload.
// Simple signaling relay logic on the server
wss.on('connection', (ws) => {
ws.on('message', (message) => {
const data = JSON.parse(message);
// If Peer A sends an 'offer', relay it to the specific 'target' Peer B
if (data.type === 'offer' || data.type === 'answer' || data.type === 'candidate') {
const targetClient = connectedClients.get(data.targetId);
if (targetClient) {
targetClient.send(JSON.stringify({
type: data.type,
payload: data.payload,
senderId: ws.id
}));
}
}
});
});
Critical Implementation Details
- Identification: You must maintain a map of
clientIdtosocketinstances. This allows you to route messages precisely rather than broadcasting them to every connected user. - Transparency: Treat the SDP payload as an opaque object. Your server should not attempt to parse or validate the contents of the SDP; it should simply relay the stringified JSON to the intended recipient.
- ICE Candidates: Alongside SDP, you will also relay "ICE candidates"—tiny snippets of network path data—to help peers bypass NAT firewalls.
Key Takeaway: A signaling server acts solely as a mailbox, relaying opaque handshake tokens between peers to initiate a direct connection, never touching the actual data stream once the WebRTC tunnel is open.