我正在使用WebRTC。我的音频和视频工作正常。我尝试添加一个数据通道。
我在冰处理设置之后和创建offer之前使用了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.dataChannel和this.myConnection

发布于 2016-03-08 11:45:21
我猜您正在犯的错误是在两端都创建了数据通道,而在另一端通过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();<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<div id='log'></div>
附注:code in fiddle,取自jib的answer的代码并进行了修改。
https://stackoverflow.com/questions/35858158
复制相似问题