UI Thread Hangs During Large File Transfers in P2P Websites

25 Views Asked by At

I Am Building A P2P File Sharing Website With The Help Of WebRTC For My Personal Project. When attempting to send large files from the side that initiated the connection, the UI thread experiences temporary hangs. After a period of delay, the UI thread returns to normal operation. However, when sending large files from the Remote Connection Side there are no issues with lag, and the process works smoothly. Please Help!!!!

This Is The Sender Side Code

async function send(buffer, file) {
    while (buffer.byteLength) {
      if (dataChannel.bufferedAmount > dataChannel.bufferedAmountLowThreshold) {
        dataChannel.onbufferedamountlow = () => {
          dataChannel.onbufferedamountlow = null;
          send(buffer, file);
        };
        return;
      }
      const chunk = buffer.slice(0, chunkSize);
      buffer = buffer.slice(chunkSize, buffer.byteLength);
      console.log(buffer.byteLength);
      dataChannel.send(chunk);
      
    }
  }
  async function sendFile() {
    // console.log(file);
    receivedSize = 0;
    if (dataChannel && dataChannel.readyState === 'open') {
      file = fileInput;
      const fileInfo = {
        'file': {
          name: file.name,
          size: file.size
        },
      };
      dataChannel.send(JSON.stringify(fileInfo));
      // setting offer in firestore for roomID
      // await userRef.update(fileInfo);
      console.log('Sending', file);

      file.arrayBuffer().then(buffer => {
        send(buffer, file);
      });
      //send(file);
      // creating buffer for file
    } else {
      file = fileInput;
      const fileInfo = {
        'file': {
          name: file.name,
          size: file.size
        },
      };
      remoteConnection.dataChannel.send(JSON.stringify(fileInfo));
      // setting offer in firestore for roomID
      // await userRef.update(fileInfo);
      console.log('Sending', file);

      file.arrayBuffer().then(buffer => {
        sendFromRemote(buffer, file);
      });
    }
  }

Reciever Side Code

fileChunks.push(e.data);
receivedSize += e.data.byteLength;
console.log("messsage received!!!" + e.data)
console.log(receivedSize);
if (receivedFile && receivedSize === receivedFileSize) {
      const file = new Blob(fileChunks);
      fileChunks = []
      receivedSize = 0;
      const url = URL.createObjectURL(file);
      const anchor = document.createElement('a');
      anchor.href = url;
      anchor.download = receivedFile; // Set the desired file name here
      document.body.appendChild(anchor);
      anchor.click();
      document.body.removeChild(anchor);
      URL.revokeObjectURL(url);
}

Tried To Search Through Stackoverflow And Internet But Got No Working Result.

0

There are 0 best solutions below