【问题标题】:How do I initiate a WebRTC data channel?如何启动 WebRTC 数据通道?
【发布时间】:2015-02-28 19:55:36
【问题描述】:

我正在尝试使用 Web 套接字在客户端之间创建 WebRTC 数据通道。

我列出了一些 ICE 服务器

var rtcsettings = {
  iceServers: [
    {url: "stun:stun.ekiga.net"},
    {url: "stun:stun.voipbuster.com"},
    {url: "stun:stun.1.google.com:19302"},
  ]   
};

然后有一个连接函数,它创建一个通道并提供并通过网络套接字发送它。

function(them) {
  var pc = new RTCPeerConnection(rtcsettings);
  self.channel = pc.createDataChannel("gamelink");
  console.log(pc, self.channel);
  self.peerconnection = pc;
  pc.createOffer(function(offer) {
    pc.setLocalDescription(new RTCSessionDescription(offer), function() {
      self.socket.send(JSON.stringify({
        "to": them,
        "uuid": uuid,
        "offer": offer,
      }));
    }, pc.close);
  }, pc.close);
}

然后在另一端有一个回调,将报价添加到其连接并发送响应。

它还为添加数据通道时设置回调,但这永远不会触发。我错过了什么?

function (message){
  var offer = message.offer;
  var pc = new RTCPeerConnection(rtcsettings);
  pc.ondatachannel = function(ch) {
    self.channel = ch;
    console.log(self.channel);
  }
  console.log(pc);
  pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
    pc.createAnswer(function(answer) {
      pc.setLocalDescription(new RTCSessionDescription(answer), function() {
        self.socket.send(JSON.stringify({
          "to": message.uuid,
          "uuid": uuid,
          "answer": answer,
        }));
      }, pc.close);
    }, pc.close);
  }, pc.close);
  self.peerconnection = pc;
}

最后在发起者上还有另一个回调,将响应描述符添加到其连接中。

function(message) {
  self.peerconnection.setRemoteDescription(
      new RTCSessionDescription(message.answer),
      function() { },
      self.peerconnection.close);
}

除了套接字内容和数据通道内容之外的所有代码几乎一字不差地取自 MDN Basic Usage 页面。

我在 localhost 上使用 Chrome 进行测试,所以防火墙应该不是问题。

交换发生后,两个连接都设置了本地和远程描述符。数据通道readyStateconnecting。 PeerConnection 的iceConnectionStatenew,它的signalingStatestable

缺少什么?

【问题讨论】:

    标签: javascript webrtc rtcdatachannel


    【解决方案1】:

    你需要处理 ICE 候选人。

    两端都需要这样的回调:

    pc.onicecandidate = function(e) {
      if(e.candidate) {
        self.socket.send(JSON.stringify({
          "to": message.uuid,
          "uuid": uuid,
          "candidate": e.candidate,
        }));
      }
    };
    

    处理程序

    callbacks["candidate"] = function(message) {
      console.log(message)
      self.peerconnection.addIceCandidate(new RTCIceCandidate(message.candidate));
    }
    

    【讨论】:

    • 很高兴你知道了。线索是 iceConnectionState 应该是 connected
    【解决方案2】:

    将这些设置添加到您的 RTCPeerConnection

    var optionalRtpDataChannels = {
      optional: [{RtpDataChannels: true}]
    };
    var pc = new RTCPeerConnection(rtcsetting, optionalRtpDataChannels);
    

    【讨论】:

    • 我不认为应该不再需要了。
    • RtpDataChannels 是非标准的,在 Firefox 中不受支持。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2014-01-08
    • 1970-01-01
    相关资源
    最近更新 更多