dimanche 25 octobre 2020

Javascript websocket sending duplicate data (reading from file list)

I am trying to read files from a file <input> and then send them to a server as bytes using websockets.

The problem is that the server is not receiving all the files, instead it will receive duplicates of random files.

As an example, say I select the files called "1.txt", "2.txt", and "3.txt", the server receives "1.txt" and then "3.txt" twice.

Here's the relevant part of my code:

const ws = new WebSocket('ws://127.0.0.1:8080/api/ws');

ws.onopen = () => {
    // Say how many files we are sending.
    // This always works.
    const fileCountByte = new Uint8Array(1);
    fileCountByte[0] = fileInput.files.length;
    ws.send(fileCountByte);

    // Send our file bytes.
    for (let i = 0; i < fileInput.files.length; i++) {
        const file = fileInput.files[i];
        const reader = new FileReader();
        reader.addEventListener('load', (e) => {
            ws.send(e.target.result);
        });
        reader.readAsArrayBuffer(file);
    }
};

I assumed it had something to do with the loop but I tried multiple loop types (forEach, for in, etc.) and it happens no matter what.

Just for reference, the code on the server receiving the files is a simple loop that calls read on the websocket x amount of times (where x is the number of files).




Aucun commentaire:

Enregistrer un commentaire