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
- 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.
- Data Channels
- Send arbitrary data (like files, chat messages, game data) between peers directly.
- Peer-to-Peer Connection
- Communication happens directly between browsers rather than through a central server (though signaling servers are used to establish the connection).
- Secure
- Uses encryption (SRTP) for media and secure channels for data.
Core WebRTC Components
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));
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()
RTCDataChannel
- Allows sending arbitrary data (text, files) between peers.
const dataChannel = pc.createDataChannel("chat"); dataChannel.onmessage = (event) => console.log("Message:", event.data);
- 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
- Browser A captures media (
getUserMedia
) and creates anRTCPeerConnection
. - Browser A generates an SDP offer and sends it via a signaling server to Browser B.
- Browser B receives the offer, creates an SDP answer, and sends it back.
- ICE candidates are exchanged to find the best path for P2P connection.
- 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