HTML5 中 createSignalingChannel() 的示例

javascriptweb developmentfront end scripts更新于 2024/5/16 16:58:00

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));
};

相关文章