WebRTC-RTCDataChannel的onmessage事件未触发

时间:2020-06-27 19:19:52

标签: javascript websocket webrtc stun turn

我正在尝试编写WebRTC的基本实现,以使用RTCDataChannel发送文本数据。 我的信号正常运行。在对等方上都设置了LocalDescription和RemoteDescription,icecandidate事件正确触发,并且候选冰都共享给两个对等方。 DataChannel onopen事件也会被触发。但是,当我尝试使用RTCDataChannel的send()函数发送消息时,onmessage事件不会在其他同位体上触发。

这就是我打开数据通道的方式-

private openDataChannel() {
    this.dataChannel = this.peerConnection.createDataChannel(`myDataChannel_${this.username}`, { ordered: true, protocol: 'tcp', });
    this.dataChannel.onerror = error => console.log('Data Channel Error:', error);
    this.dataChannel.onmessage = message => {
      console.log('data channel message', message);
      this.messages.push(message.data);
    };
    this.dataChannel.onopen = event => console.log('data channel opened', event);
}

我正在使用this.dataChannel.send(this.msgToSend);

发送数据

这是我创建RTCPeerConnection的部分-

this.peerConnection = new RTCPeerConnection({
    iceServers: [{ urls: 'stun:stun.stunprotocol.org:3478' }]
});
console.log('RTCPeerConnection created');
console.log(this.peerConnection);

this.peerConnection.onicecandidate = event => {
    if (event.candidate) {
      console.log('onicecandidate', event)
      this.sendToServer({
        type: 'candidate',
        candidate: event.candidate
      })
    }
}

this.openDataChannel();

在创建RTCPeerConnection并调用this.openDataChannel之后,我调用了信令服务器,通过该服务器我在两个同级上都设置了remoteDescription和localDescription。

我尝试使用 chrome:// webrtc-internals / 进行调试。在其中,我可以看到两个同位体上的两个数据通道。而且我可以看到messages每当我从其他对等方发送数据时,接收到的计数都在增加。但是,在js上,onmessage事件没有触发 enter image description here

我在这里怀疑的是,我是从 Peer B 通过myDataChannel_B发送数据的(因为这是在那里创建的数据通道)。在 peer A webrtc-internals 上,显示myDataChannel_B下的messagesReceived计数。但是,在同级A上,我订阅了myDataChannel_A的onmessage事件。这似乎很奇怪。我在这里做什么错了?

0 个答案:

没有答案