我正在尝试通过 WebRTC 共享文件,但一段时间后它停止了,并且记录 RTCDatachannel 发送队列已满

I am trying to share a file over WebRTC but after some time it stops, and log RTCDatachannel send queue is full

let file = fileUpload.files[0];
let offset = 0;
let chunkSize = 1024*1024*16;


file.arrayBuffer().then((buffer) => {
            
 while(buffer.byteLength){
                
       const chunk = buffer.slice(0, chunkSize);
       buffer = buffer.slice(chunkSize, buffer.byteLength);
      dataChannel.send(chunk);
  }
})

它适用于小文件,但适用于大文件。

A DataChannel 有一个 bufferedAmount 属性 告诉你还有多少字节等待发送。它还有一个名为 bufferedAmountLowThreshold 的 属性。

The RTCDataChannel property bufferedAmountLowThreshold is used to specify the number of bytes of buffered outgoing data that is considered "low."

https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/bufferedAmountLowThreshold https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/bufferedAmount

只要 bufferedAmount 低于 bufferedAmountLowThreshold,您就可以继续正常发送数据。一旦它变大,您将停止排队更多数据,直到收到 bufferedamountlow 事件。

const send = () => {
  while (buffer.byteLength) {
    if (dataChannel.bufferedAmount > dataChannel.bufferedAmountLowThreshold) {
      dataChannel.onbufferedamountlow = () => {
        dataChannel.onbufferedamountlow = null;
        send();
      };
      return;
    }
    const chunk = buffer.slice(0, chunkSize);
    buffer = buffer.slice(chunkSize, buffer.byteLength);
    dataChannel.send(chunk);
  }
};
send();