WebRTC (Web Real-Time Communication)

WebRTC (Web Real-Time Communication) in JavaScript is a set of APIs and protocols that allows web applications to establish peer-to-peer (P2P) connections directly between browsers or devices. It enables real-time audio, video, and data sharing without requiring users to install plugins or external software.

Here’s a clear breakdown:


Key Features of WebRTC

  1. Real-time Audio and Video
    • Enables video calls and voice calls in the browser.
    • Example: Google Meet, Zoom Web, or any in-browser video chat.
  2. Data Channels
    • Send arbitrary data (like files, chat messages, game data) between peers directly.
  3. Peer-to-Peer Connection
    • Communication happens directly between browsers rather than through a central server (though signaling servers are used to establish the connection).
  4. Secure
    • Uses encryption (SRTP) for media and secure channels for data.

Core WebRTC Components

  1. getUserMedia()
    • Accesses the user’s camera and microphone.
    navigator.mediaDevices.getUserMedia({ video: true, audio: true }) .then(stream => { document.querySelector('video').srcObject = stream; }) .catch(error => console.error(error));
  2. RTCPeerConnection
    • Handles the connection between two peers, including ICE candidates, session descriptions, and media streams.
    const pc = new RTCPeerConnection(); pc.addStream(localStream); // deprecated: newer approach uses addTrack()
  3. RTCDataChannel
    • Allows sending arbitrary data (text, files) between peers.
    const dataChannel = pc.createDataChannel("chat"); dataChannel.onmessage = (event) => console.log("Message:", event.data);
  4. Signaling
    • Before peers connect, they need to exchange metadata (SDP, ICE candidates) via a server (WebSocket, HTTP, etc.).
    • WebRTC does not provide signaling itself, you must implement it.

How It Works

  1. Browser A captures media (getUserMedia) and creates an RTCPeerConnection.
  2. Browser A generates an SDP offer and sends it via a signaling server to Browser B.
  3. Browser B receives the offer, creates an SDP answer, and sends it back.
  4. ICE candidates are exchanged to find the best path for P2P connection.
  5. Once connected, media and data flow directly between browsers.

Example Use Cases

  • Video conferencing apps
  • Online multiplayer games
  • File sharing without server storage
  • Remote collaboration tools

Leave a Reply