0

We know that if you send a large file in the way below:

ws.send(file);

you may probably end up receiving an error saying it is too big and the connection is closed immediately

How will you design your application to send a large file, in FULL speed?

My solution:

async async_timeout(t) {
    return new Promise((resolve, reject) => {
        setTimeout(() => { resolve(); }, t);
    });
}
    
async wait_websocket_send(ws) {
    // 262144 must be less that the max value of WebSocket.bufferedAmount
    while (ws.bufferedAmount > 262144)
        await async_timeout(2);
}

async send_large_data(ws, data) {
    let reader = data.stream.getReader();
    while (true) {
        let chunk = await reader.read();
        if (chunk.done)
            break;
        // wait for the queued data to go
        await wait_websocket_send(ws);
        ws.send(chunk.value);
    }
}

I tested it, but it seems to transmit in a lower speed than my full bandwidth

How can I improve the performance?

aleck099
  • 428
  • 2
  • 10
  • 1
    See https://stackoverflow.com/questions/20652194/websocket-frame-size-limitation – ControlAltDel Aug 29 '22 at 15:38
  • Maybe(?) better on StackExchange CodeReview – ControlAltDel Aug 29 '22 at 15:40
  • "*you may probably end up receiving an error saying it is too big*" - what exactly is the error and where is it thrown? – Bergi Aug 29 '22 at 15:50
  • Where from did you get that value of `262144`? – Bergi Aug 29 '22 at 15:51
  • @Bergi In [MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send) it says *the socket is closed automatically*. And 262144 = 4 * 65536, where 65536 is the size of per chunk of [Streams API](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API) – aleck099 Aug 29 '22 at 16:10
  • Ah I see. A shame there's no way to access the size of the actual buffer… – Bergi Aug 29 '22 at 16:22
  • Related: https://stackoverflow.com/questions/61996515/how-to-measure-websocket-backpressure-or-network-buffer-from-client – Bergi Aug 29 '22 at 16:22

0 Answers0