将属性附加到通过DataChannel

时间:2017-06-19 11:34:13

标签: javascript webrtc arraybuffer

我目前正在接收来自视频流的块,我通过DataChannel发送给同伴,然后他将在另一端重建视频。

我让这部分工作得很好,但我想补充一下这是收到的那些块,以便它们碰巧以不同于预期的顺序到达时无关紧要。

最初我认为添加参数chunkId会起作用,但是当我在接收器端执行.data.chunkId时,它是未定义的。

然后我尝试使用chunkId将ArrayBuffer和JSON.stringify({ "chunkId": chunkId, "data": chunk })字符串化,但是当我在另一端解析它时会导致问题(Unexpected end of JSON inputUnexpected token , in JSON at position #)< / p>

DataChannels也接受blob,所以我想我会尝试,但发件人正在使用node.js,显然不能这样做。我无法弄清楚如何解决这个问题。

我尝试的最后一件事是简单地将chunkId附加到ArrayBuffer本身的开头/结尾但是当我尝试创建一个新数组时,我在尝试添加时遇到错误source is too large大块头。

实现这一目标的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

你应该能够混合发送文本和ArrayBuffers,并在接收时检查它们:

var pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();

pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.oniceconnectionstatechange = e => log(pc1.iceConnectionState);
pc1.onnegotiationneeded = e =>
  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(e => log(e));

var dc1 = pc1.createDataChannel("chat", {negotiated: true, id: 0});
var dc2 = pc2.createDataChannel("chat", {negotiated: true, id: 0});

dc2.binaryType = "arraybuffer";
dc2.onmessage = e => {
  if (e.data instanceof ArrayBuffer) {
    log("Got ArrayBuffer!");
  } else if (e.data instanceof Blob) {
    log("Got Blob!");
  } else {
    log("> " + e.data);
  }
}

button.onclick = e => dc1.send(new ArrayBuffer(8));
chat.onkeypress = e => {
  if (e.keyCode != 13) return;
  dc1.send(chat.value);
  chat.value = "";
};

var log = msg => div.innerHTML += "<br>" + msg;
Chat: <input id="chat"><button id="button">Send ArrayBuffer</button><br>
<div id="div"></div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

那么为什么不在每个ArrayBuffer之前发送块ID?