【问题标题】:Websocket progress pauses when switching tabs on browser (client)在浏览器(客户端)上切换选项卡时,Websocket 进度暂停
【发布时间】:2018-01-27 09:16:09
【问题描述】:

我面临着一种前所未有的非同寻常的副作用。让我彻底描述一下:

客户端(浏览器)有一个输入标签,用于选择文件。单击特定按钮时,会发出一个动作,其中这些文件通过 websockets(通过库 Socket.io)传输到服务器。

// Starts an upload after clicking on an upload button.
async upload() {
    if (this.state.fileList.length === 0) { return; }

    // Dispatch a start uploading action.
    this.props.startUp();

    // We map original files from the state's file list.
    let originFiles = _.map(this.state.fileList, (file: any) => {
        return file.originFileObj;
    });

    // Send files over the socket streams to the server.
    await ApiService.upload(originFiles, () => {
        // Update the state whenever a file has been uploaded.
        this.setState({ ...this.state, finishedFiles: this.state.finishedFiles + 1 })
    });

    this.clearItemList();
    // Dispatch an end uploading action.
    this.props.endUp();
}

每当单击按钮时都会调用此函数。如您所见,有一个 api 服务,它在该文件列表上被调用,并将这些文件流式传输到服务器。文件通过套接字流式传输。

import * as io from 'socket.io-client';
import * as ios from 'socket.io-stream';

export function upload(data: any[], onUpload?: () => void): Promise<any> {
    return new Promise((res, rej) => {
        const up = io.connect("ws://localhost:8000/");
        // Right after we connect.
        up.on('connect', () => {
            // Connect to the upload socket point.
            up.emit('upload', {});
            // Whenever we receive an 'ok' status, we send files over the wire.
            up.on('ok', async () => {
                // If we sent all the files, notify the server to end.
                if (data.length === 0) {
                    up.emit('end', {});
                    up.disconnect();
                    // Resolve this promise.
                    res();
                // Otherwise, emit a 'data' action, that sends the files.
                } else {
                    let blob = data.pop();
                    let stream = ios.createStream();
                    ios(up).emit('data', stream, { size: blob.size });
                    ios.createBlobReadStream(blob, { highWaterMark: 500000 }).pipe(stream);
                    // Callback for the onUpload event.
                    onUpload();
                }
            });
            up.on('error', () => {
                rej();
            });
        });
    });
}

一切正常,直到我在客户端(浏览器)上切换选项卡并且进度暂停。切换到客户端选项卡后,进度会自动恢复。

我的同事推测,这可能是浏览器本身的问题,当我失去标签的焦点时,它会停止传输文件。

任何关于如何解决这个问题和/或稍微调整代码的想法都将不胜感激。

谢谢。

【问题讨论】:

  • 如果您的系统内存不足并且您使用的是 Chrome,您可能需要考虑查看chrome://flags/#automatic-tab-discarding
  • 我尝试禁用此选项,但仍然没有成功。

标签: javascript node.js reactjs socket.io


【解决方案1】:

它不会暂停流,只会减慢它的速度。在 Chrome 中检查此选项:“--disable-background-timer-throttling”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-19
    • 2015-03-17
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多