我目前正在从通过DataChannel发送给对等方的视频流中接收大块,该对等方将在另一端重建视频。
我的这部分工作正常,但是我想添加接收到的#块,以便它们碰巧到达的顺序与预期的顺序无关。
最初,我认为添加参数chunkId
是可行的,但是当我在接收方执行.data.chunkId
时,它是未定义的。
然后,我尝试使用chunkId
将ArrayBuffer与JSON.stringify({ "chunkId": chunkId, "data": chunk })
一起进行字符串化,但是当我在另一端(Unexpected end of JSON input
和Unexpected token , in JSON at position #
)对其进行解析时会导致问题
DataChannels也接受blob,所以我想我会尝试一下,但是发送者正在使用node.js,显然不能这样做。我不是很想办法解决这个问题。
我尝试的最后一件事是简单地将chunkId
追加到ArrayBuffer本身的开头/结尾,但是当我尝试创建新数组时,尝试添加块本身时出现错误source is too large
。
实现此目标的正确方法是什么?
最佳答案
您应该能够混合发送文本和ArrayBuffer,并在接收时检查它们:
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?