A Simple Hands-On for Understanding WebRTC

Contents

Introduction

In this post, I go over the basics of WebRTC, signaling servers, and WebSocket, and build a minimal demo with Next.js.

What is WebRTC?

WebRTC (Web Real-Time Communication) is a mechanism for browsers to exchange data such as audio and video directly with each other (P2P).

  • Even if browsers talk to each other directly, how does one find the other?
  • You need signaling.

What is signaling?

It exchanges the information needed to connect, such as:

  • SDP(offer/answer): information such as which video/audio codecs can be used
  • ice-candidate: IP and port information that can be used for the connection

The signaling server relays this exchange.

Any transport works for it, e.g. WebSocket / REST API / Socket.io.

Summary of the signaling server's role

  • It helps exchange information before the connection.
  • It does not carry the actual data (video, audio).
  • You can implement it with anything, such as WebSocket or HTTP.
  • Once the exchange is done, the browsers talk to each other directly.
[Browser A] ⇄ (SDP exchange over WebSocket) ⇄ [Signaling server] ⇄ [Browser B]
         ↖───────────── WebRTC (video/audio P2P) ─────────────↗

How it differs from WebSocket

Item WebSocket WebRTC
Communication Client ⇄ server Browser ⇄ browser (P2P)
Data path Goes through the server Direct connection (can also go via TURN)
Use cases Chat, notifications, real-time sync, etc. Video calls, voice calls, data transfer, etc.

A minimal hands-on with Next.js

This time, I build a minimal WebRTC app that uses text data, so you can try it on a single PC.

Since this hands-on is for understanding the basics, the code is not split into files and is messy. Please bear with me.

1. Set up the project

First, create a Next.js project and install the packages you need.

npx create-next-app@latest webrtc-demo
cd webrtc-demo
# Install ws for the signaling server, and concurrently to start the server and client together
npm i ws
npm i -D concurrently

Edit the scripts in package.json so that Next.js and the signaling server start with a single command.

{
  "scripts": {
    "dev": "concurrently \"node server/signaling-server.js\" \"next dev\"",
    "build": "next build",
    "start": "next start"
  }
}

2. Implement the signaling server

I implement the signaling server with the ws library. Create a server directory at the project root and put signaling-server.js in it.

import { WebSocketServer } from "ws";

//Start the WebSocket server. rooms is a list that tracks "who is in which room"
const wss = new WebSocketServer({ port: 3001 });
const rooms = new Map();

// Join a room
function joinRoom(ws, roomId) {
  if (!rooms.has(roomId)) rooms.set(roomId, new Set());
  rooms.get(roomId).add(ws);
  ws.roomId = roomId;
}

// Relay signaling messages
function broadcastToRoom(ws, msgObj) {
  const set = rooms.get(ws.roomId);
  if (!set) return;
  for (const client of set) {
    // Forward to everyone except yourself
    if (client !== ws && client.readyState === client.OPEN) {
      client.send(JSON.stringify(msgObj));
    }
  }
}

wss.on("connection", (ws) => {
  ws.on("message", (data) => {
    const msg = JSON.parse(data.toString());

    const { type, roomId, payload } = msg;

    if (type === "join") {
      joinRoom(ws, roomId);
      return;
    }

    // Relay offer / answer / ice to the other peer
    if (type === "offer" || type === "answer" || type === "ice") {
      broadcastToRoom(ws, { type, payload });
    }
  });
});

3. Implement the client side (Next.js)

I edit page.tsx so that it handles "connecting to the signaling server", "establishing the WebRTC (P2P) connection", and "sending and receiving chat messages".

import { useRef, useState } from "react";

// Type of the messages sent to and received from the signaling server over WebSocket
// type tells the kinds of messages apart
type Signal =
  | { type: "join"; roomId: string } // Join a room
  | { type: "offer"; payload: RTCSessionDescriptionInit } // SDP offer
  | { type: "answer"; payload: RTCSessionDescriptionInit } // SDP answer
  | { type: "ice"; payload: RTCIceCandidateInit }; // ICE candidate

// Type of one chat message
type ChatMessage = {
  sender: "me" | "other";
  text: string;
};

export default function Home() {
  const [roomId, setRoomId] = useState("");
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [inputText, setInputText] = useState("");
  // Whether the WebSocket is connected
  const [connected, setConnected] = useState(false);
  // State of the DataChannel (the P2P side)
  const [channelStatus, setChannelStatus] = useState<"closed" | "open">(
    "closed"
  );

  // Holds the WebSocket instance (useRef so the same one is used across re-renders)
  const wsRef = useRef<WebSocket | null>(null);
  // Holds the RTCPeerConnection instance
  const pcRef = useRef<RTCPeerConnection | null>(null);
  // Holds the P2P DataChannel (for chat)
  const dataChannelRef = useRef<RTCDataChannel | null>(null);

  // Helper that adds to the array of displayed messages
  const addMessage = (text: string, sender: "me" | "other") => {
    setMessages((prev) => [...prev, { sender, text }]);
  };

  // Sets up the DataChannel events
  //  - When a message arrives: onmessage
  //  - When the channel opens: onopen
  const setupDataChannel = (dc: RTCDataChannel) => {
    // When a message arrives from the other peer
    dc.onmessage = (ev) => addMessage(ev.data, "other");
    // When the channel opens (enable the Send button, etc.)
    dc.onopen = () => setChannelStatus("open");
    // Keep a reference to use when sending
    dataChannelRef.current = dc;
  };

  // Creates the WebRTC RTCPeerConnection and sets up its events
  const createPeerConnection = () => {
    const pc = new RTCPeerConnection();

    // On the receiving side, the event that receives the DataChannel the other peer created
    pc.ondatachannel = (ev) => setupDataChannel(ev.channel);

    // Called when an ICE candidate is found
    // Notify the other peer of the candidate via the signaling server
    pc.onicecandidate = (ev) => {
      if (ev.candidate) wsSend({ type: "ice", payload: ev.candidate.toJSON() });
    };

    pcRef.current = pc;
    return pc;
  };

  // Shared function that sends signaling messages over WebSocket
  // Sends roomId too, so the server can route messages per room
  const wsSend = (msg: Signal) => {
    wsRef.current?.send(JSON.stringify({ ...msg, roomId }));
  };

  // Connect to the signaling server (WebSocket)
  const connectSignaling = () => {
    const ws = new WebSocket("ws://localhost:3001");
    wsRef.current = ws;

    // When the WebSocket connection is established
    ws.onopen = () => {
      // Send the join-room message
      wsSend({ type: "join", roomId });
      setConnected(true);
    };

    // When a signaling message arrives
    ws.onmessage = async (ev) => {
      const msg: Signal = JSON.parse(ev.data);
      const pc = pcRef.current ?? createPeerConnection();

      if (msg.type === "offer") {
        // Receiving side (offer received)
        // Set the SDP sent by the other peer as the remote description
        await pc.setRemoteDescription(msg.payload);
        // Create our own answer
        const answer = await pc.createAnswer();
        await pc.setLocalDescription(answer);
        // Send the answer back to the other peer
        wsSend({ type: "answer", payload: answer });
      } else if (msg.type === "answer") {
        // Calling side (answer received)
        await pc.setRemoteDescription(msg.payload);
      } else if (msg.type === "ice") {
        // When an ICE candidate arrives from the other peer
        await pc.addIceCandidate(msg.payload);
      }
    };
  };

  // The side that starts the chat
  //  - Create the PeerConnection
  //  - Create the DataChannel
  //  - Create and send the offer
  const startCall = async () => {
    const pc = createPeerConnection();
    // The calling side creates the DataChannel
    const dc = pc.createDataChannel("chat");
    // Set up the DataChannel events, etc.
    setupDataChannel(dc);

    // Generate the SDP offer and set it locally
    const offer = await pc.createOffer();
    await pc.setLocalDescription(offer);
    // Send it to the other peer via the signaling server
    wsSend({ type: "offer", payload: offer });
  };

  // Send a chat message
  const sendMessage = () => {
    // Send to the other peer over the P2P DataChannel
    dataChannelRef.current?.send(inputText);
    // Also add the message to our own screen
    addMessage(inputText, "me");
    // Clear the input
    setInputText("");
  };

  return (
    <main
      style={{
        padding: 24,
        maxWidth: 600,
        margin: "0 auto",
        fontFamily: "sans-serif",
      }}
    >
      <h1>WebRTC Data Channel Chat</h1>
      <p>テキストチャットでP2P通信を検証します。</p>

      <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
        <input
          value={roomId}
          onChange={(e) => setRoomId(e.target.value)}
          placeholder="Room ID"
          style={{ padding: 8 }}
        />
        <button
          onClick={connectSignaling}
          disabled={connected}
          style={{ padding: "8px 16px" }}
        >
          {connected ? "WS Connected" : "1. Connect WS"}
        </button>
        <button
          onClick={startCall}
          disabled={!connected || channelStatus === "open"}
          style={{ padding: "8px 16px" }}
        >
          1. Start Call (Offer)
        </button>
      </div>

      <div
        style={{
          border: "1px solid #ccc",
          borderRadius: 8,
          padding: 16,
          height: 300,
          overflowY: "auto",
          background: "#f9f9f9",
          marginBottom: 16,
        }}
      >
        {messages.length === 0 && (
          <div style={{ color: "#888" }}>No messages yet.</div>
        )}
        {messages.map((m, i) => (
          <div
            key={i}
            style={{
              textAlign: m.sender === "me" ? "right" : "left",
              marginBottom: 8,
            }}
          >
            <span
              style={{
                background: m.sender === "me" ? "#dcf8c6" : "#fff",
                padding: "6px 12px",
                borderRadius: 12,
                display: "inline-block",
                border: "1px solid #ddd",
              }}
            >
              {m.text}
            </span>
          </div>
        ))}
      </div>

      <div style={{ display: "flex", gap: 8 }}>
        <input
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && sendMessage()}
          placeholder="Type a message..."
          disabled={channelStatus !== "open"}
          style={{ flex: 1, padding: 8 }}
        />
        <button
          onClick={sendMessage}
          disabled={channelStatus !== "open"}
          style={{ padding: "8px 16px" }}
        >
          Send
        </button>
      </div>

      <div
        style={{
          marginTop: 12,
          fontSize: 12,
          color: channelStatus === "open" ? "green" : "red",
        }}
      >
        P2P Status: {channelStatus.toUpperCase()}
      </div>
    </main>
  );
}

Message types sent to the signaling server

type What for? When is it sent?
join Gather users in the same room Right after the WS connects
offer I want to start a P2P connection! (Caller → Callee) On Start Call
answer Reply to the offer (Callee → Caller) After receiving the offer
ice Candidate network paths for P2P (ICE Candidate) Sent automatically during WebRTC negotiation

4. Try it out

  1. Start the server
npm run dev
  1. Open two tabs in the browser
  • Open http://localhost:3000 in two tabs (or windows).
  1. Connection steps
    • Tab A: click "Connect WS"
    • Tab B: click "Connect WS"
    • Tab A: click "Start Call (Offer)"
  2. Chat
    • When the status turns OPEN, the P2P connection has succeeded.
    • When you send a message, it shows up in the other tab right away. Two browser tabs running the WebRTC Data Channel Chat demo side by side. A message sent from the left tab shows up in the right tab, and both show P2P Status: OPEN.

Communicating across NAT

In this hands-on, the communication was local to local, so it wasn't needed. But when you want to communicate between different networks across NAT, there are cases where you need STUN / TURN servers.

What are STUN / TURN servers?

STUN / TURN servers have the following roles.

Name Role
STUN (Session Traversal Utilities for NATs) Finds out your own IP / port as seen from outside
TURN (Traversal Using Relay around NAT) Acts as a relay server and carries the communication on your behalf

How a STUN server works


     ┌─────────────────────┐                     ┌─────────────────────┐
     │      Browser A      │                     │      Browser B      │
     └──────────┬──────────┘                     └─────────────────────┘
 "What is my    │   ▲
  IP address?"  │   │  "Your IP address is X.X.X.X"
                │   │
           ┌─────────┐
           │   NAT   │
           └─────────┘
                │   │
                │   │
                ▼   │
       ┌────────────┴──────┐
       │    STUN server    │
       └───────────────────┘

How a TURN server works


     ┌─────────────────────┐                     ┌─────────────────────┐
     │      Browser A      │  ───────×────────   │      Browser B      │
     └──────────┬──────────┘                     └──────────┬──────────┘
                │                                           │
           ┌─────────┐                                 ┌─────────┐
           │   NAT   │                                 │   NAT   │
           └─────────┘                                 └─────────┘
                │                                           │
                │          ┌────────────────────┐           │
                └──────────│    TURN server     │───────────┘
                           └────────────────────┘

I didn't use it in this hands-on, but you can also specify a STUN server by writing it like this:

const pc = new RTCPeerConnection({
  iceServers: [
    { urls: "stun:stun.l.google.com:19302" },    // STUN
    { 
      urls: "turn:example.com:3478",             // TURN
      username: "user",
      credential: "password"
    }
  ],
});

Article I referred to: https://qiita.com/okyk/items/a405f827e23cb9ef3bde (Japanese)

Translated from the Japanese original.

Thanks. I'll look into it.

Spotted a mistake?

Tell me what's wrong and I'll fix it. Only I see what you send.