HTML5 中的 createSignalingChannel() 示例


Web RTC 需要瀏覽器之間的點對點通訊。這種機制需要信令、網路資訊、會話控制和媒體資訊。Web 開發人員可以選擇不同的機制在瀏覽器之間進行通訊,例如 SIP 或 XMPP 或任何雙向通訊。createSignalingChannel() 的示例

var signalingChannel = createSignalingChannel();
var pc;
var configuration = ...;

// run start(true) to initiate a call
function start(isCaller) {
   pc = new RTCPeerConnection(configuration);
   // send any ice candidates to the other peer
   pc.onicecandidate = function (evt) {
      signalingChannel.send(JSON.stringify({ "candidate": evt.candidate }));
   };
   
   // once remote stream arrives, show it in the remote video element
   pc.onaddstream = function (evt) {
      remoteView.src = URL.createObjectURL(evt.stream);
   };

   // get the local stream, show it in the local video element and send it
   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));
};

更新於: 2020-01-29

115 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.