WebRTC - RTCDataChannel 的 onmessage 事件没有触发。

4
我正在尝试编写一个基本的WebRTC实现,使用 RTCDataChannel 发送文本数据。 我的信令正常工作。 LocalDescription和RemoteDescription在两个对等方上设置,并且icecandidate事件正确触发,并且ice候选项被共享到两个对等方。 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/进行调试, 在其中我可以看到两个数据通道,并且每当我从另一个对等方发送数据时,我可以看到messagesReceived计数器在增加。但是,在js中,onmessage事件没有触发。 enter image description here 我怀疑这里的问题是我从peer B通过myDataChannel_B发送数据(因为在那里创建了该数据通道)。在peer A中,webrtc-internals显示myDataChannel_B下的messagesReceived计数器。但是,在peer A上,我订阅了myDataChannel_A的onmessage事件。这似乎很奇怪。我在这里做错了什么?

嗨!你找到什么了吗?我们遇到了同样的问题。 - Nahum Bazes
1个回答

0
我也遇到了完全相同的问题,结果发现我在连接的每一侧都创建了一个单独的数据通道。
正如createDataChannel示例中所概述的那样,如果您尝试通过连接的任一侧创建数据通道,它们将需要共享一个id值,例如0
// Both sides
const pc = new RTCPeerConnection(options);
const channel = pc.createDataChannel("chat", { negotiated: true, id: 0 });

值得注意的是,只有在远程对等方创建数据通道时,才会触发ondatachannel回调或datachannel事件,而不是在您本地创建通道时。当negotiated设置为true时,不会触发ondatachannel事件。有关更多详细信息,请参阅datachannel event
如果成功,查看chrome://webrtc-internals/应该只显示一个RTCDataChannel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接