我正在尝试使用WebRTC's adapter.js使用RTCPeerConnection
通过RTCDataChannel
发送文字,但我收到以下错误:
Uncaught InvalidStateError:
Failed to execute 'send' on 'RTCDataChannel':
RTCDataChannel.readyState is not 'open'
我的代码可通过this fiddle及以下版本获取:
var peerConnection = new RTCPeerConnection(null, {
optional: [{
RtpDataChannels: true
}]
});
peerConnection.ondatachannel = function(event) {
receiveChannel = event.channel;
receiveChannel.onmessage = function(event){
alert(event.data);
};
};
var dataChannel = peerConnection.createDataChannel("data", {reliable: false});
dataChannel.send("Hello");
我做错了吗?
答案 0 :(得分:5)
我今天早上编写了以下代码,在单个页面中使用了RTCPeerConnection
和RTCDataChannel
。声明这些函数的顺序很重要。
var localPeerConnection, remotePeerConnection, sendChannel, receiveChannel;
localPeerConnection = new RTCPeerConnection(null, {
optional: [{
RtpDataChannels: true
}]
});
localPeerConnection.onicecandidate = function(event) {
if (event.candidate) {
remotePeerConnection.addIceCandidate(event.candidate);
}
};
sendChannel = localPeerConnection.createDataChannel("CHANNEL_NAME", {
reliable: false
});
sendChannel.onopen = function(event) {
var readyState = sendChannel.readyState;
if (readyState == "open") {
sendChannel.send("Hello");
}
};
remotePeerConnection = new RTCPeerConnection(null, {
optional: [{
RtpDataChannels: true
}]
});
remotePeerConnection.onicecandidate = function(event) {
if (event.candidate) {
localPeerConnection.addIceCandidate(event.candidate);
}
};
remotePeerConnection.ondatachannel = function(event) {
receiveChannel = event.channel;
receiveChannel.onmessage = function(event) {
alert(event.data);
};
};
localPeerConnection.createOffer(function(desc) {
localPeerConnection.setLocalDescription(desc);
remotePeerConnection.setRemoteDescription(desc);
remotePeerConnection.createAnswer(function(desc) {
remotePeerConnection.setLocalDescription(desc);
localPeerConnection.setRemoteDescription(desc);
});
});
答案 1 :(得分:1)
您不能只创建peerConnection,dataChannel并立即开始使用它。 顺便说一句,你在这里没有2个同伴......
我建议从阅读this开始,它将为您提供基本概念的知识 接着Sam Dutton继续this很棒的代码实验室。
更新以回答mhenry的请求: 以下是在一个类中设置数据通道的全部内容:https://gist.github.com/shacharz/9661930 按照评论,你只需要: