What is WebRTC and when would you use it?

Topic: microservices, Real-Time Communication. Level: Hard.

Answer

WebRTC enables **peer-to-peer**, low-latency audio/video/data directly between browsers (no media relay through your server in the common case). Key pieces: **getUserMedia** (capture), **RTCPeerConnection** (the P2P media/data channel over UDP/SRTP), **ICE/STUN/TURN** (NAT traversal — STUN discovers public IPs, TURN relays when P2P fails), and a **signaling** channel (you build this, often via WebSocket) to exchange SDP offers/answers and ICE candidates. Use it for video calls, live streaming, screen sharing, and P2P file transfer. It's complex and needs STUN/TURN infrastructure. ```js const pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] }) // 1. Signaling (via YOUR channel, e.g. WebSocket) exchanges these: const offer = await pc.createOffer(); await pc.setLocalDescription(offer) signal.send({ sdp: offer }) // -> peer pc.onicecandidate = e => e.candidate && signal.send({ ice: e.candidate }) // 2. Media/data then flows peer-to-peer, not through your server: pc.ontrack = e => remoteVideo.srcObject = e.streams[0] ```