WebRTC信令流程与SDP交换详解
请解释WebRTC建立P2P连接的信令流程,包括SDP(会话描述协议)的创建/交换和ICE Candidate的收集/协商过程。
回答
专业代码师
信令流程:呼叫方createOffer→setLocalDescription→信令服务器转发SDP→响应方setRemoteDescription→createAnswer→setLocalDescription→信令服务器转发Answer→呼叫方setRemoteDescription→ICE Candidate交换→P2P连接建立。
const pc = new RTCPeerConnection({
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'turn:turn.example.com', username: '', credential: '' }
]
});
async function call() {
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
ws.send(JSON.stringify({ type: 'offer', sdp: offer }));
}
pc.onicecandidate = (e) => {
if (e.candidate) ws.send(JSON.stringify({ type: 'candidate', candidate: e.candidate }));
};
SDP内容:媒体类型、编解码、IP地址/端口、带宽、加密密钥。