🌍 Networking

WebRTC

Web Real-Time Communication

A technology that enables P2P real-time communication in browsers without plugins. Bypasses NAT with ICE/STUN/TURN and exchanges SDP through signaling. Used for video conferencing and screen sharing in Zoom and Google Meet.

📖 Detailed Explanation

WebRTC (Web Real-Time Communication) is an open-source technology that enables real-time P2P (Peer-to-Peer) communication in browsers and mobile apps without plugins. Google began developing it in 2011, and it is now standardized by the W3C and IETF and supported by all major browsers, including Chrome, Firefox, Safari, and Edge.

WebRTC has three core components. MediaStream captures audio/video streams from the camera and microphone. RTCPeerConnection handles media transmission between peers and is responsible for encryption, codecs, and NAT traversal. RTCDataChannel transmits arbitrary data, such as text and files, bidirectionally.

A signaling process is required to establish a P2P connection. In it, two peers exchange connection information, and WebRTC itself does not define a signaling method. It can be implemented in any way, such as WebSocket, HTTP polling, or Firebase. During signaling, SDP (Session Description Protocol) messages are exchanged to negotiate media information such as codecs, resolution, and ports.

In NAT (Network Address Translation) environments, the ICE (Interactive Connectivity Establishment) framework is used for P2P connections. A STUN (Session Traversal Utilities for NAT) server tells a peer its public IP and port, and when a direct connection is not possible, a TURN (Traversal Using Relays around NAT) server acts as a relay. Typically, 80% of connections are resolved with STUN, and the remaining 20% use TURN.

WebRTC is widely used in video calls, screen sharing, and real-time collaboration tools such as Zoom, Google Meet, Discord, and Facebook Messenger. All media is encrypted with SRTP (Secure Real-time Transport Protocol), which ensures security.

🏗️ WebRTC Connection Architecture

┌─────────────────────────────────────────────────────────────────────────────┐
│                         WebRTC P2P 연결 흐름                              │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   Peer A (Browser)                         Peer B (Browser)                │
│   ┌─────────────┐                           ┌─────────────┐                │
│   │ getUserMedia│                           │ getUserMedia│                │
│   │ (카메라/마이크)│                           │ (카메라/마이크)│                │
│   └──────┬──────┘                           └──────┬──────┘                │
│          │                                         │                        │
│          ▼                                         ▼                        │
│   ┌─────────────┐                           ┌─────────────┐                │
│   │RTCPeerConn- │                           │RTCPeerConn- │                │
│   │ection       │                           │ection       │                │
│   └──────┬──────┘                           └──────┬──────┘                │
│          │                                         │                        │
│          │         ┌───────────────────┐          │                        │
│          │         │  Signaling Server  │          │                        │
│          │         │   (WebSocket 등)    │          │                        │
│          │         └─────────┬─────────┘          │                        │
│          │                   │                     │                        │
│          │◄─────Offer SDP────┼────Offer SDP─────►│                        │
│          │◄─────Answer SDP───┼────Answer SDP────►│                        │
│          │◄────ICE Candidates─┼───ICE Candidates──►│                        │
│          │                   │                     │                        │
│          │         ┌─────────┴─────────┐          │                        │
│          │         │   STUN Server      │          │                        │
│          │         │ (공인 IP 확인)        │          │                        │
│          │         └─────────┬─────────┘          │                        │
│          │                   │                     │                        │
│          │◄───────Public IP/Port───────►│                        │
│          │                                         │                        │
│          │    ┌─────────────────────────┐         │                        │
│          │    │  TURN Server (Fallback) │         │                        │
│          │    │  (P2P 실패 시 릴레이)      │         │                        │
│          │    └───────────┬─────────────┘         │                        │
│          │                │                        │                        │
│          └────────────────┼────────────────────────┘                        │
│                           │                                                 │
│             ════════════════════════════════                            │
│                P2P Media Stream (암호화됨)                              │
│                - Video/Audio (SRTP)                                    │
│                - DataChannel (SCTP/DTLS)                               │
│             ════════════════════════════════                            │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

───► 시그널링 (연결 정보 교환)    ═══► P2P 미디어 스트림

💻 Code Example

// WebRTC P2P 화상통화 기본 구현
const config = {
    iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },  // Google STUN 서버
        { urls: 'stun:stun1.l.google.com:19302' },
        // TURN 서버 (필요 시)
        {
            urls: 'turn:your-turn-server.com:3478',
            username: 'user',
            credential: 'password'
        }
    ]
};

// RTCPeerConnection 생성
const peerConnection = new RTCPeerConnection(config);

// 1. 로컬 미디어 스트림 획득
async function startLocalStream() {
    const stream = await navigator.mediaDevices.getUserMedia({
        video: { width: 1280, height: 720 },
        audio: true
    });

    // 로컬 비디오에 표시
    document.getElementById('localVideo').srcObject = stream;

    // PeerConnection에 트랙 추가
    stream.getTracks().forEach(track => {
        peerConnection.addTrack(track, stream);
    });

    return stream;
}

// 2. ICE Candidate 이벤트 처리
peerConnection.onicecandidate = (event) => {
    if (event.candidate) {
        // 시그널링 서버를 통해 상대방에게 전달
        signalingChannel.send({
            type: 'ice-candidate',
            candidate: event.candidate
        });
    }
};

// 3. 원격 스트림 수신
peerConnection.ontrack = (event) => {
    document.getElementById('remoteVideo').srcObject = event.streams[0];
};

// 4. Offer 생성 (호출자)
async function createOffer() {
    const offer = await peerConnection.createOffer();
    await peerConnection.setLocalDescription(offer);

    // 시그널링 서버로 Offer 전송
    signalingChannel.send({
        type: 'offer',
        sdp: offer.sdp
    });
}

// 5. Answer 생성 (수신자)
async function handleOffer(offer) {
    await peerConnection.setRemoteDescription(
        new RTCSessionDescription({ type: 'offer', sdp: offer.sdp })
    );

    const answer = await peerConnection.createAnswer();
    await peerConnection.setLocalDescription(answer);

    signalingChannel.send({
        type: 'answer',
        sdp: answer.sdp
    });
}

// 6. Answer 처리 (호출자)
async function handleAnswer(answer) {
    await peerConnection.setRemoteDescription(
        new RTCSessionDescription({ type: 'answer', sdp: answer.sdp })
    );
}

// 7. ICE Candidate 처리
async function handleIceCandidate(candidate) {
    await peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
}

// 연결 상태 모니터링
peerConnection.onconnectionstatechange = () => {
    console.log('Connection state:', peerConnection.connectionState);
    // 'connected' | 'disconnected' | 'failed' | 'closed'
};
// Node.js 시그널링 서버 (Socket.IO)
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
    cors: { origin: '*' }
});

const rooms = new Map();

io.on('connection', (socket) => {
    console.log('User connected:', socket.id);

    // 방 참가
    socket.on('join-room', (roomId) => {
        socket.join(roomId);

        if (!rooms.has(roomId)) {
            rooms.set(roomId, new Set());
        }
        rooms.get(roomId).add(socket.id);

        // 기존 참가자들에게 알림
        socket.to(roomId).emit('user-joined', socket.id);

        // 기존 참가자 목록 전송
        const existingUsers = [...rooms.get(roomId)].filter(id => id !== socket.id);
        socket.emit('existing-users', existingUsers);
    });

    // Offer 전달
    socket.on('offer', ({ targetId, sdp }) => {
        io.to(targetId).emit('offer', {
            senderId: socket.id,
            sdp
        });
    });

    // Answer 전달
    socket.on('answer', ({ targetId, sdp }) => {
        io.to(targetId).emit('answer', {
            senderId: socket.id,
            sdp
        });
    });

    // ICE Candidate 전달
    socket.on('ice-candidate', ({ targetId, candidate }) => {
        io.to(targetId).emit('ice-candidate', {
            senderId: socket.id,
            candidate
        });
    });

    // 연결 해제
    socket.on('disconnect', () => {
        rooms.forEach((users, roomId) => {
            if (users.has(socket.id)) {
                users.delete(socket.id);
                socket.to(roomId).emit('user-left', socket.id);
            }
        });
    });
});

server.listen(3000, () => {
    console.log('Signaling server running on port 3000');
});
// 화면 공유 구현
async function startScreenShare() {
    try {
        // 화면 캡처 스트림 획득
        const screenStream = await navigator.mediaDevices.getDisplayMedia({
            video: {
                cursor: 'always',  // 마우스 커서 표시
                displaySurface: 'monitor'  // 전체 화면 | 'window' | 'tab'
            },
            audio: true  // 시스템 오디오 (브라우저 지원에 따라)
        });

        // 기존 비디오 트랙을 화면 공유로 교체
        const videoTrack = screenStream.getVideoTracks()[0];
        const sender = peerConnection.getSenders().find(
            s => s.track?.kind === 'video'
        );

        if (sender) {
            await sender.replaceTrack(videoTrack);
        }

        // 화면 공유 중단 감지
        videoTrack.onended = () => {
            console.log('Screen sharing stopped');
            stopScreenShare();
        };

        return screenStream;
    } catch (error) {
        if (error.name === 'NotAllowedError') {
            console.log('User denied screen sharing');
        }
        throw error;
    }
}

// DataChannel로 파일 전송
function setupDataChannel() {
    const dataChannel = peerConnection.createDataChannel('fileTransfer', {
        ordered: true,  // 순서 보장
        maxRetransmits: 3  // 재전송 횟수
    });

    dataChannel.onopen = () => {
        console.log('DataChannel opened');
    };

    dataChannel.onmessage = (event) => {
        // 수신된 데이터 처리
        const data = JSON.parse(event.data);
        if (data.type === 'file-chunk') {
            handleFileChunk(data);
        }
    };

    // 파일을 청크로 나누어 전송
    async function sendFile(file) {
        const chunkSize = 16384;  // 16KB 청크
        const reader = new FileReader();
        let offset = 0;

        // 파일 메타데이터 전송
        dataChannel.send(JSON.stringify({
            type: 'file-start',
            name: file.name,
            size: file.size,
            mimeType: file.type
        }));

        // 청크 단위로 전송
        while (offset < file.size) {
            const chunk = file.slice(offset, offset + chunkSize);
            const buffer = await chunk.arrayBuffer();

            dataChannel.send(JSON.stringify({
                type: 'file-chunk',
                data: Array.from(new Uint8Array(buffer)),
                offset
            }));

            offset += chunkSize;
        }

        dataChannel.send(JSON.stringify({ type: 'file-end' }));
    }

    return { dataChannel, sendFile };
}

// 연결 품질 통계
async function getConnectionStats() {
    const stats = await peerConnection.getStats();

    stats.forEach(report => {
        if (report.type === 'inbound-rtp' && report.kind === 'video') {
            console.log('Video Stats:', {
                framesReceived: report.framesReceived,
                framesDropped: report.framesDropped,
                bytesReceived: report.bytesReceived,
                packetsLost: report.packetsLost
            });
        }
    });
}

🗣️ Say It Like This in Practice

💬 In a Video Conferencing System Design Meeting
"There are about 20% of cases where a direct WebRTC connection is not possible, so a TURN server is essential. You can use a TURN service such as Twilio or Xirsys, or build your own with coturn. Bandwidth costs add up considerably, so they need to be included in the budget plan."
💬 In an Interview
"To explain the WebRTC connection flow, first we exchange the SDP Offer/Answer through the signaling server. At this point, information such as media codecs and resolution is negotiated. At the same time, we gather ICE Candidates, check the public IP using the STUN server, and exchange the ICE Candidates of both sides to find the optimal connection path. In a Symmetric NAT environment, we use a TURN relay."
💬 In a Troubleshooting Meeting
"If the ICE connection state keeps getting stuck at 'checking', it is highly likely either a STUN server response problem or that the UDP port is blocked by a firewall. Check the ICE candidate gathering logs in chrome://webrtc-internals, and also verify that the TURN server fallback works properly."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Deploying Without a TURN Server

In Symmetric NAT and corporate firewall environments, STUN alone cannot establish a connection. In real production environments, about 20% of connections require TURN. Be sure to set up a TURN server or use a cloud service.

❌
Ignoring the Signaling Order

Calling addIceCandidate before setRemoteDescription causes an error. ICE Candidates must be added after the SDP exchange is complete. Use a pattern that stores candidates in a queue and processes them later.

❌
Not Applying HTTPS

getUserMedia works only over HTTPS, except on localhost. Apply HTTPS even in development environments, using ngrok or a self-signed certificate. Over HTTP, media permission requests are automatically denied.

✅
Recommended Implementation

Using a WebRTC PaaS such as Twilio, Agora, or Daily.co includes TURN infrastructure and signaling. When building it yourself, a combination of coturn + Socket.IO is common. Be sure to implement connection state monitoring and automatic reconnection logic.

🔗 Related Terms

📚 Learn More