3 min read

WebRTC (Web Real-Time Communication)

WebRTC is an open source project that enables real-time communication of audio, video, and data in Web and native apps. It allows Peer-to-Peer (P2P) communication directly between browsers without requiring an intermediate server to relay the media stream (though servers are needed for the initial setup).

1. The Three Main APIs

MediaStream (getUserMedia)

Used to access the user's camera and microphone.

navigator.mediaDevices.getUserMedia({ video: true, audio: true })
  .then(stream => {
    const videoElement = document.querySelector('video');
    videoElement.srcObject = stream;
  })
  .catch(error => {
    console.error('Error accessing media devices.', error);
  });

RTCPeerConnection

The core of WebRTC. It handles the connection between peers, maintains the session, and handles bandwidth management and encryption.

const configuration = { 
  iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] 
};
const peerConnection = new RTCPeerConnection(configuration);

RTCDataChannel

Allows bidirectional transfer of arbitrary data (text, files, binary) between peers. It works like WebSockets but is P2P and supports both reliable (TCP-like) and unreliable (UDP-like) modes.

const dataChannel = peerConnection.createDataChannel("chat");

dataChannel.onopen = () => console.log("Channel opened");
dataChannel.onmessage = (event) => console.log("Received:", event.data);

2. Signaling

WebRTC does not specify how peers find each other. You need a separate mechanism (like WebSockets or HTTP) to exchange connection information before the P2P link is established. This process is called Signaling.

Peers exchange two types of data via the signaling server:

  1. Session Description Protocol (SDP): Describes the media capabilities (codecs, resolutions) and connection properties.
    • Offer: Initiator sends an offer.
    • Answer: Receiver sends an answer.
  2. ICE Candidates: Network information (IP addresses, ports) needed to route packets.

3. NAT Traversal (STUN and TURN)

Most devices are behind NATs (Network Address Translators) and don't have public IP addresses.

  • STUN (Session Traversal Utilities for NAT): A lightweight server that tells a client "Here is your public IP address". This works for most simple NATs.
  • TURN (Traversal Using Relays around NAT): If a direct P2P connection fails (e.g., strict corporate firewalls), traffic is relayed through a TURN server. This consumes bandwidth and costs money.

4. Basic Connection Flow

  1. Peer A creates an RTCPeerConnection.
  2. Peer A creates an Offer (SDP) and sets it as localDescription.
  3. Peer A sends the Offer to Peer B (via Signaling Server).
  4. Peer B receives the Offer and sets it as remoteDescription.
  5. Peer B creates an Answer (SDP) and sets it as localDescription.
  6. Peer B sends the Answer to Peer A (via Signaling Server).
  7. Peer A receives the Answer and sets it as remoteDescription.
  8. Simultaneously, both peers gather ICE Candidates and send them to each other as they are discovered.

5. Use Cases

  • Video Conferencing (Google Meet, Zoom).
  • P2P File Sharing (Sharedrop).
  • Real-time Multiplayer Games (low latency).
  • Screen Sharing.

programming/javascript/vanilla/javascript programming/javascript/vanilla/websockets programming/javascript/vanilla/file-api