WebRTC(Web Real-Time Communication)는 브라우저 간의 실시간 P2P 통신을 지원하는 기술입니다. 이를 통해 별도의 플러그인 없이 브라우저에서 실시간 오디오, 비디오, 데이터 통신을 가능하게 합니다.
Offer
Answer
ICE Candidate
Signaling 서버란?
Socket.io의 활용
1. React 클라이언트와 Flask 서버 연결
socket.emit()으로 메시지를 전송.socketio.on()으로 메시지를 수신 후 상대 클라이언트에게 전달.2. Signaling 과정
3. P2P 연결 완료
// Offer 생성 및 설정
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
// RemoteDescription 설정
await peerConnection.setRemoteDescription(offer);
미디어 데이터 전송
: WebRTC를 사용해 실시간 비디오 및 오디오 데이터를 전송.
데이터 채널 전송
: 텍스트 데이터, 파일 등 일반 데이터를 전송 가능.
const peerConnection = new RTCPeerConnection({
iceServers: [
{ urls: "stun:stun.l.google.com:19302" },
{ urls: "turn:turnserver.example.com", username: "user", credential: "pass" },
],
});
import React, { useRef } from "react";
import io from "socket.io-client";
const socket = io("http://localhost:5000");
const WebRTCApp = () => {
const localVideoRef = useRef(null);
const remoteVideoRef = useRef(null);
const startCall = async () => {
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
localVideoRef.current.srcObject = stream;
const peerConnection = new RTCPeerConnection({
iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
});
stream.getTracks().forEach((track) => peerConnection.addTrack(track, stream));
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
socket.emit("offer", offer);
socket.on("answer", async (answer) => {
await peerConnection.setRemoteDescription(answer);
});
peerConnection.onicecandidate = (event) => {
if (event.candidate) socket.emit("candidate", event.candidate);
};
socket.on("candidate", async (candidate) => {
await peerConnection.addIceCandidate(candidate);
});
peerConnection.ontrack = (event) => {
remoteVideoRef.current.srcObject = event.streams[0];
};
};
return (
<div>
<video ref={localVideoRef} autoPlay muted></video>
<video ref={remoteVideoRef} autoPlay></video>
<button onClick={startCall}>Start Call</button>
</div>
);
};
export default WebRTCApp;
from flask import Flask
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")
@app.route("/")
def index():
return "WebRTC Signaling Server is Running"
@socketio.on("offer")
def handle_offer(data):
socketio.emit("offer", data, broadcast=True)
@socketio.on("answer")
def handle_answer(data):
socketio.emit("answer", data, broadcast=True)
@socketio.on("candidate")
def handle_candidate(data):
socketio.emit("candidate", data, broadcast=True)
if __name__ == "__main__":
socketio.run(app, host="0.0.0.0", port=5000)
React + Socket.io + Flask 조합은 WebRTC 프로젝트에 적합한 강력한 조합입니다.
확장성
Signaling 서버로서 역할을 수행하며, React와 연동해 실시간 통신 구현.
호환성
Electron을 통해 패드에서도 동일한 화면 제공 가능.
효율성
Signaling 이후 P2P로 데이터 전송, 서버 부하 감소와 지연 시간 최소화.