无法通过数据渠道获取消息

时间:2016-03-08 03:04:28

标签: javascript webrtc

我正在使用WebRTC。我的音频和视频效果很好。我尝试添加数据通道。

我在冰处理设置之后和创建商品之前使用openDataChannel()函数。

// setup ice handling
this.myConnection.onicecandidate = (ev) => {
    if (ev.candidate) {
        this.send({
            type: 'candidate',
            candidate: ev.candidate
        });
    }
};
this.openDataChannel();

// openDataChannel()

openDataChannel() {
    let dataChannelOptions = {
        reliable: true
    };
    this.dataChannel = this.myConnection.createDataChannel('myLabel', dataChannelOptions);

    this.dataChannel.onerror = (err) => {
        console.log(err);
    };

    this.dataChannel.onmessage = (ev) => {
        console.log('Got message ', ev.data);
    };

    this.dataChannel.onopen = () => {
        console.log('Data Channel is opened.');
        console.log('this.dataChannel', this.dataChannel);   // Screenshot below
        console.log('this.myConnection', this.myConnection); // Screenshot below
        this.dataChannel.send('Hello!');
    };

    this.dataChannel.onclose = () => {
        console.log('Data Channel is closed.');
    };
}

在最新的Chrome和Opera中,数据通道可以正确打开和关闭。但是其他用户无法获得消息。并且没有出现任何错误。

在Firefox中,很奇怪,数据通道正常打开,但在7或8秒后,数据通道自动关闭(音频和视频仍在工作)。

这会导致什么?感谢

以下是this.dataChannelthis.myConnection

enter image description here

1 个答案:

答案 0 :(得分:2)

我猜你所犯的错误是在两端创建数据通道而不是通过ondatachannel在另一端接受,你最终得到两个悬空数据通道发送消息,但没有人正在监听另一方侧。看一下下面的例子,适用于chrome和firefox:



"use strict";
let pc1 = new RTCPeerConnection()
  , pc2 = new RTCPeerConnection()
  , div = document.getElementById('log')
  , add = (pc, can) => can && pc.addIceCandidate(can).catch(log)
  , log = msg => div.innerHTML += "<br>" + msg
  , exchangeSDP = () => pc1.createOffer().then(d => pc1.setLocalDescription(d))
      .then(() => pc2.setRemoteDescription(pc1.localDescription))
      .then(() => pc2.createAnswer()).then(d => pc2.setLocalDescription(d))
      .then(() => pc1.setRemoteDescription(pc2.localDescription))
      .catch(log)
  , setChannelEvents = (dataChannel, label) => {
          dataChannel.onerror = log;
          dataChannel.onclose = () => log(`Data Channel is closed: ${label}`);
          dataChannel.onmessage = ev => log(`${label}, Got message:  ${ev.data}`);
          dataChannel.onopen = () => log(`Data Channel is opened: ${label}`);          
          setTimeout(() => dataChannel.send('Hello from '+label), 3000);
      }
  
pc1.onicecandidate = e => add(pc2, e.candidate);
pc2.onicecandidate = e => add(pc1, e.candidate);
pc1.oniceconnectionstatechange = e => log(pc1.iceConnectionState);
setChannelEvents( pc1.createDataChannel('label', { reliable: true }), 'Peer1');
pc2.ondatachannel = evt => setChannelEvents(evt.channel, 'Peer2');
exchangeSDP();
&#13;
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<div id='log'></div>
&#13;
&#13;
&#13;

P.S:code in fiddle,代码来自jib&#39; s answer并已修改。