Web RTC需要浏览器之间的对等通信。该机制需要信令,网络信息,会话控制和媒体信息。Web开发人员可以选择不同的机制在浏览器之间进行通信,例如SIP或XMPP或任何两种方式的通信。一个例子createSignalingChannel()
:
var signalingChannel = createSignalingChannel(); var pc; var configuration = ...; //运行start(true)发起呼叫 function start(isCaller) { pc = new RTCPeerConnection(configuration); //将任何求职者发送给其他同行 pc.onicecandidate = function (evt) { signalingChannel.send(JSON.stringify({ "candidate": evt.candidate })); }; //远程流到达后,将其显示在远程视频元素中 pc.onaddstream = function (evt) { remoteView.src = URL.createObjectURL(evt.stream); }; //获取本地流,在本地视频元素中显示并发送 navigator.getUserMedia({ "audio": true, "video": true }, function (stream) { selfView.src = URL.createObjectURL(stream); pc.addStream(stream); if (isCaller) pc.createOffer(gotDescription); else pc.createAnswer(pc.remoteDescription, gotDescription); function gotDescription(desc) { pc.setLocalDescription(desc); signalingChannel.send(JSON.stringify({ "sdp": desc })); } }); } signalingChannel.onmessage = function (evt) { if (!pc) start(false); var signal = JSON.parse(evt.data); if (signal.sdp) pc.setRemoteDescription(new RTCSessionDescription(signal.sdp)); else pc.addIceCandidate(new RTCIceCandidate(signal.candidate)); };