webrtcp2ppeerjsreal-time-datasimple-peer

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);
  }
})

it works fine for small files but stops with big size files.


Solution

  • A DataChannel has a bufferedAmount property which tells you how many bytes are still waiting to be sent. It also has a property called 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

    You could keep sending data as normal as long as bufferedAmount is below bufferedAmountLowThreshold. Once it is larger you stop queuing more data until you receive a bufferedamountlow event.

    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();