无法通过数据通道获取消息
我正在使用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.');
};
}
在最新铬和歌剧,数据信道可以打开和关闭正确。但其他用户无法收到消息。并没有出现错误。
在Firefox中,它很奇怪,数据通道正常打开,但7或8秒后,数据通道自动关闭(音频和视频仍在工作)。
这是什么原因造成的?由于
下面是this.dataChannel
和this.myConnection
:
我猜你是做的错误是在两端创造datachannel和不接受任何通过ondatachannel
另一端,你最终有两个悬挂发送消息的数据通道,但没有人在另一侧收听。看看下面的例子中,工作在Chrome和Firefox:从臂架的answer和修改采取code in fiddle,代码:
"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();
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<div id='log'></div>
P.S。
谢谢,@mido,我想你猜可能会更正。但是在代码中,唯一能确保一个用户与另一个正确用户连接的是当使用'this.myConnection.createDataChannel'时。我错过了什么吗? (我还在我的问题中添加了'this.myConnection'的屏幕截图,与您的代码中显示的控制台中的'pc1'和'pc2'相同。) –
嗯,有什么方法可以知道是否有人连接与此用户以及谁在数据通道中与此用户连接? –
@HongboMiao你可以通过'this.myConnection.ondatachannel'来做到这一点...... – mido
您是否在创建报价之前创建数据通道? – mido
嗨@mido对于调用者来说,是的,我在创建优惠之前创建了数据通道。对于被调用者,我在获得offer后立即创建了datachannel。我的控制台可以显示“数据通道已打开”,但无法获得消息 –