我正在尝试编写一个基本的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
事件没有触发。
我怀疑这里的问题是我从peer B通过myDataChannel_B发送数据(因为在那里创建了该数据通道)。在peer A中,webrtc-internals显示myDataChannel_B下的messagesReceived计数器。但是,在peer A上,我订阅了myDataChannel_A的onmessage
事件。这似乎很奇怪。我在这里做错了什么?