在浏览器(客户端)上切换选项卡时,Websocket 进度暂停



我面临着以前从未遇到过的非常特殊的副作用。让我彻底描述一下:

客户端(浏览器(有一个输入标记,用于选择文件。单击特定按钮时,将发出一个操作,其中这些文件通过 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 中选中此选项:"--禁用后台定时器限制">

最新更新