首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RTCDataChannel的ReadyState未‘打开’

RTCDataChannel的ReadyState未‘打开’
EN

Stack Overflow用户
提问于 2014-03-18 12:19:14
回答 2查看 9.4K关注 0票数 11

我尝试使用WebRTC's adapter.js通过带有RTCDataChannelRTCPeerConnection发送文本,但收到以下错误:

代码语言:javascript
复制
Uncaught InvalidStateError:
Failed to execute 'send' on 'RTCDataChannel':
RTCDataChannel.readyState is not 'open'

我的代码可以通过this fiddle和下面的代码获得:

代码语言:javascript
复制
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");

我做错什么了吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-18 22:13:29

今天早上,我编写了以下代码,在单个页面中使用RTCPeerConnectionRTCDataChannel。声明这些函数的顺序很重要。

代码语言:javascript
复制
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);
  });
});
票数 10
EN

Stack Overflow用户

发布于 2014-03-18 16:22:54

你不能只创建peerConnection、dataChannel,然后马上开始使用它。顺便说一句,你在这里没有两个同龄人。

  1. 您需要在2个对等点中创建peerConnections对象
  2. Transfer SDP's
  3. get ice candidates
  4. ,只有在dataChannel打开之后,您才能在其上发送信息<

>G29

我建议从阅读this开始,它会让你了解基本概念,然后继续山姆·达顿的this And代码实验室。

更新以响应mhenry的请求:以下是在一个类中设置数据通道的全部内容:https://gist.github.com/shacharz/9661930遵循注释,您只需:

Handlmessage添加信令,将sdp的ice候选发送到您希望通过更高级别的逻辑处理所有连接中断之类的其他对等点。

  • 确保在接收到sdp时调用“

  • ”方法

  • 将该类与其公共方法一起使用: SetupCall,Send,Close
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22470291

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档