Home ยป HTML5 WebRTC Tutorial

HTML5 WebRTC Tutorial

by shedders

WebRTC (Web Real-Time Communication) is a technology that enables real-time peer-to-peer communication between browsers and devices.

It supports audio, video, and data sharing without requiring plugins.

In this tutorial, you’ll learn:

  1. What is WebRTC and how it works.
  2. Setting up a basic WebRTC connection.
  3. Sharing audio and video streams.
  4. Sending data between peers using DataChannels.
  5. Practical examples and best practices.

1. What is WebRTC?

WebRTC allows direct communication between browsers or devices for tasks like:

  • Audio and video calls.
  • Live streaming.
  • File sharing.

Key Components:

  1. RTCPeerConnection: Manages connections and streams.
  2. MediaStream API: Captures media like audio or video.
  3. RTCDataChannel: Sends data between peers.

2. Setting Up a WebRTC Connection

To establish a WebRTC connection:

  1. Create Peer Connections: Use RTCPeerConnection on both peers.
  2. Exchange ICE Candidates: Share network information to establish a connection.
  3. Exchange Session Descriptions: Share offer/answer to establish communication.

Example 1: Basic WebRTC Setup

JavaScript

const configuration = {
    iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
};

const localConnection = new RTCPeerConnection(configuration);
const remoteConnection = new RTCPeerConnection(configuration);

// Handle ICE Candidates
localConnection.onicecandidate = (event) => {
    if (event.candidate) {
        remoteConnection.addIceCandidate(event.candidate);
    }
};

remoteConnection.onicecandidate = (event) => {
    if (event.candidate) {
        localConnection.addIceCandidate(event.candidate);
    }
};

// Handle Connection
remoteConnection.ondatachannel = (event) => {
    const receiveChannel = event.channel;
    receiveChannel.onmessage = (e) => console.log("Message from Local:", e.data);
};

// Create DataChannel
const dataChannel = localConnection.createDataChannel("chat");
dataChannel.onopen = () => console.log("DataChannel Opened");
dataChannel.onmessage = (e) => console.log("Message from Remote:", e.data);

// Create Offer
localConnection.createOffer().then((offer) => {
    localConnection.setLocalDescription(offer);
    remoteConnection.setRemoteDescription(offer);

    return remoteConnection.createAnswer();
}).then((answer) => {
    remoteConnection.setLocalDescription(answer);
    localConnection.setRemoteDescription(answer);
});

// Send a Message
setTimeout(() => {
    dataChannel.send("Hello, WebRTC!");
}, 2000);

Explanation:

  1. STUN Server: Helps discover public IP addresses for NAT traversal.
  2. RTCPeerConnection: Establishes a connection between peers.
  3. DataChannel: Sends and receives messages.

3. Sharing Audio and Video Streams

WebRTC allows you to share media streams using the getUserMedia API.

Example 2: Audio/Video Communication

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebRTC Audio/Video</title>
</head>
<body>
    <h1>WebRTC Video Call</h1>
    <video id="localVideo" autoplay muted playsinline></video>
    <video id="remoteVideo" autoplay playsinline></video>
    <script src="videoRTC.js"></script>
</body>
</html>

JavaScript (videoRTC.js)

const configuration = {
    iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
};

const localVideo = document.getElementById("localVideo");
const remoteVideo = document.getElementById("remoteVideo");

const localConnection = new RTCPeerConnection(configuration);
const remoteConnection = new RTCPeerConnection(configuration);

// Add ICE Candidates
localConnection.onicecandidate = (event) => {
    if (event.candidate) {
        remoteConnection.addIceCandidate(event.candidate);
    }
};

remoteConnection.onicecandidate = (event) => {
    if (event.candidate) {
        localConnection.addIceCandidate(event.candidate);
    }
};

// Add Remote Stream
remoteConnection.ontrack = (event) => {
    remoteVideo.srcObject = event.streams[0];
};

// Capture Local Media
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then((stream) => {
    localVideo.srcObject = stream;

    // Add Tracks to the Local Connection
    stream.getTracks().forEach((track) => localConnection.addTrack(track, stream));

    // Create Offer
    localConnection.createOffer().then((offer) => {
        localConnection.setLocalDescription(offer);
        remoteConnection.setRemoteDescription(offer);

        return remoteConnection.createAnswer();
    }).then((answer) => {
        remoteConnection.setLocalDescription(answer);
        localConnection.setRemoteDescription(answer);
    });
}).catch((error) => {
    console.error("Error accessing media devices:", error);
});

Explanation:

  1. getUserMedia: Captures video/audio streams from the user’s device.
  2. addTrack: Adds media tracks to the connection.
  3. ontrack: Receives media tracks from the remote peer.

4. Sending Data Using DataChannels

WebRTC supports peer-to-peer data transfer using RTCDataChannel.

Example 3: Chat Application with DataChannel

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebRTC Chat</title>
</head>
<body>
    <h1>WebRTC Chat</h1>
    <textarea id="chatLog" rows="10" cols="50" readonly></textarea><br>
    <input id="message" type="text" placeholder="Type a message">
    <button id="send">Send</button>
    <script src="chatRTC.js"></script>
</body>
</html>

JavaScript (chatRTC.js)

const configuration = {
    iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
};

const chatLog = document.getElementById("chatLog");
const messageInput = document.getElementById("message");
const sendButton = document.getElementById("send");

const localConnection = new RTCPeerConnection(configuration);
const remoteConnection = new RTCPeerConnection(configuration);

localConnection.onicecandidate = (event) => {
    if (event.candidate) {
        remoteConnection.addIceCandidate(event.candidate);
    }
};

remoteConnection.onicecandidate = (event) => {
    if (event.candidate) {
        localConnection.addIceCandidate(event.candidate);
    }
};

// Setup DataChannel
const dataChannel = localConnection.createDataChannel("chat");
dataChannel.onmessage = (event) => {
    chatLog.value += `Remote: ${event.data}\n`;
};

remoteConnection.ondatachannel = (event) => {
    const receiveChannel = event.channel;
    receiveChannel.onmessage = (event) => {
        chatLog.value += `Remote: ${event.data}\n`;
    };
};

// Create Offer
localConnection.createOffer().then((offer) => {
    localConnection.setLocalDescription(offer);
    remoteConnection.setRemoteDescription(offer);

    return remoteConnection.createAnswer();
}).then((answer) => {
    remoteConnection.setLocalDescription(answer);
    localConnection.setRemoteDescription(answer);
});

// Send Message
sendButton.addEventListener("click", () => {
    const message = messageInput.value;
    chatLog.value += `You: ${message}\n`;
    dataChannel.send(message);
    messageInput.value = "";
});

Explanation:

  1. dataChannel.send(data): Sends data to the remote peer.
  2. onmessage: Listens for incoming messages.

5. Practical Example: File Sharing

Use RTCDataChannel to send files between peers.

Example 4: File Sharing

  • dataChannel.send(file.slice(start, end)): Splits large files into chunks for transmission.

6. Best Practices

  1. Use STUN/TURN Servers:
    • STUN: Discovers public IP.
    • TURN: Relays traffic if direct communication fails.
  2. Handle Errors Gracefully:
    • Check for media permissions and network availability.
  3. Security:
    • Use HTTPS for secure connections.
    • Verify the identity of peers.
  4. Test Network Conditions:
    • Simulate various network environments for better performance.

7. Browser Support

Feature Chrome Firefox Safari Edge
WebRTC Yes Yes Yes Yes
DataChannel Yes Yes Yes Yes
Audio/Video Yes Yes Yes Yes

8. Conclusion

In this tutorial, you learned:

  1. The basics of WebRTC.
  2. How to create a peer connection.
  3. How to share audio, video, and data using WebRTC.

WebRTC is a powerful tool for real-time communication.

You may also like