2 min read
Core Components of WebRTC
Part of project: WebRTC Guide

The Building Blocks of WebRTC

WebRTC consists of several key components that work together to enable real-time communication. Understanding these components is essential for implementing WebRTC in your applications.

1. MediaStream (getUserMedia)

The MediaStream API (often accessed via navigator.mediaDevices.getUserMedia()) allows you to capture media from the user’s camera and microphone.

async function getLocalMedia() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({
      audio: true,
      video: true
    });
    
    // Attach the stream to a video element
    document.querySelector('video').srcObject = stream;
    return stream;
  } catch (err) {
    console.error('Error accessing media devices:', err);
  }
}

2. RTCPeerConnection

RTCPeerConnection is the core component that establishes and maintains a connection between peers. It handles:

  • Signal processing
  • Codec handling
  • Peer-to-peer communication
  • Security
  • Bandwidth management
// Create peer connections for both peers
const pc1 = new RTCPeerConnection();
const pc2 = new RTCPeerConnection();

// Add tracks from the local stream to the peer connection
localStream.getTracks().forEach(track => {
  pc1.addTrack(track, localStream);
});

// Listen for remote tracks
pc2.ontrack = (event) => {
  document.querySelector('#remoteVideo').srcObject = event.streams[0];
};

3. RTCDataChannel

RTCDataChannel enables bidirectional data transfer between peers. It’s useful for:

  • Text chat
  • File transfer
  • Game state synchronization
  • Any application data exchange
// Create a data channel
const dataChannel = pc1.createDataChannel("myChannel");

dataChannel.onopen = () => {
  console.log("Data channel is open");
  dataChannel.send("Hello from peer 1!");
};

dataChannel.onmessage = (event) => {
  console.log("Message received:", event.data);
};

// The other peer listens for the channel
pc2.ondatachannel = (event) => {
  const receivedChannel = event.channel;
  receivedChannel.onmessage = (e) => {
    console.log("Message from peer 1:", e.data);
    receivedChannel.send("Hello from peer 2!");
  };
};

In the next article, we’ll explore the signaling process - the mechanism that allows peers to find and connect to each other.