WebRTC
Peer-to-peer connections, video calls, screen sharing, and data channels.
Overview
WebRTC enables real-time peer-to-peer communication.
Key Concepts
- RTCPeerConnection — Peer-to-peer connection
- MediaStream — Audio/video streams
- DataChannel — Arbitrary data transfer
- ICE — NAT traversal
- Signaling — Connection establishment
Code Examples
<video id="localVideo" autoplay muted playsinline></video>
<video id="remoteVideo" autoplay playsinline></video>
<button id="startCall">Start Call</button>
<button id="endCall">End Call</button>
<script>
const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');
let peerConnection;
// Get local stream
async function getLocalStream() {
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true
});
localVideo.srcObject = stream;
return stream;
}
// Create peer connection
function createPeerConnection(stream) {
const config = {
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
};
peerConnection = new RTCPeerConnection(config);
// Add local stream
stream.getTracks().forEach(track => {
peerConnection.addTrack(track, stream);
});
// Handle remote stream
peerConnection.ontrack = (event) => {
remoteVideo.srcObject = event.streams[0];
};
// Handle ICE candidates
peerConnection.onicecandidate = (event) => {
if (event.candidate) {
// Send to signaling server
console.log('ICE candidate:', event.candidate);
}
};
return peerConnection;
}
// Start call
document.getElementById('startCall').addEventListener('click', async () => {
const stream = await getLocalStream();
peerConnection = createPeerConnection(stream);
// Create offer
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
console.log('Offer created:', offer);
// Send offer to remote peer via signaling server
});
// End call
document.getElementById('endCall').addEventListener('click', () => {
peerConnection?.close();
localVideo.srcObject = null;
remoteVideo.srcObject = null;
});
// Screen sharing
async function shareScreen() {
const stream = await navigator.mediaDevices.getDisplayMedia({
video: true
});
const videoTrack = stream.getVideoTracks()[0];
peerConnection.getSenders().forEach(sender => {
if (sender.track.kind === 'video') {
sender.replaceTrack(videoTrack);
}
});
}
</script>
Practice
Build a video calling application with WebRTC.