WebRTC Signaling Deep Dive
Implement WebRTC signaling: SDP exchange, ICE candidate trickle, and state synchronization.
What you'll learn
- Signaling server design (not part of WebRTC spec)
- SDP offer/answer exchange flow
- ICE candidate trickle ICE vs vanilla ICE
- Perfect negotiation pattern to avoid glare
Concept
WebRTC Signaling Deep Dive
Signaling exchanges connection information between peers before P2P connection. WebRTC does not specify a signaling protocol - you implement it, typically via WebSocket.
The Signaling Flow
Peer A creates SDP offer -> server forwards to B -> B creates answer -> server forwards to A -> both exchange ICE candidates -> media flows.
Trickle ICE
With vanilla ICE, wait for all candidates before sending SDP. With trickle ICE, send candidates as discovered, speeding up connection. Modern WebRTC always uses trickle.
Perfect Negotiation
Glare occurs when both peers negotiate simultaneously. Use polite/impolite flags: the impolite peer continues, the polite peer rolls back. This prevents deadlocks.
State Synchronization
Both peers track state: have I sent an offer? received an answer? A state machine prevents sending offers when not in stable state.
Example
let makingOffer = false; const polite = true;
const pc = new RTCPeerConnection();
pc.onnegotiationneeded = async () => { try { makingOffer = true; await pc.setLocalDescription(await pc.createOffer()); console.log('Sent offer, state:', pc.signalingState); } finally { makingOffer = false; } };
async function handleSignaling(desc) { const d = JSON.parse(desc); const collision = d.type==='offer' && (makingOffer || pc.signalingState!=='stable'); if (!polite && collision) return; await pc.setRemoteDescription(d); if (d.type==='offer') { await pc.setLocalDescription(await pc.createAnswer()); console.log('Sent answer'); } }
pc.onicecandidate = (e) => { if (e.candidate) console.log('Candidate:', e.candidate.candidate.slice(0,40)); };
console.log('Perfect negotiation ready, polite:', polite);
The perfect negotiation pattern uses makingOffer flag to handle simultaneous offers. The polite peer defers to the impolite peer during glare.
Try it
- JSON Formatter
Signaling messages (SDP, ICE) are JSON - format for debugging.
Common mistakes
The mistake
Sending an offer when not in stable state.
The fix
Check pc.signalingState before creating an offer. Must be stable.
The mistake
Not handling glare (simultaneous offers).
The fix
Without perfect negotiation, simultaneous offers can deadlock. Always implement polite/impolite pattern.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.