将Socket.io和webpack与nodejs一起使用时,CPU使用率达到100%

时间:2019-09-11 08:37:06

标签: node.js webpack socket.io

我在后端使用socket.io(v2.2.0)和express(4.17.1)。我的前端使用webpack,内部使用sockJS进行热重装。在第一个IO连接上,CPU达到100%使用率。 从前端,我们试图通过套接字连接发送视频片段,该视频片段在后端进行处理。以下是前端代码。

前端代码:

async uploadFile() {
                this.isLoading = true;
                let counter = 0;
                let chunkSize = 1000000;
                this.socket = this.io(window.socketendpoint, {
                    query: {
                        token: this.$cookies.get('token')
                    }
                });
                for (let start = 0; start < this.upload.chosen.size; start += chunkSize) {
                    let chunk = this.upload.chosen.slice(start, start + chunkSize);
                    this.socket.emit('UPLOAD_CHUNK', {
                        data: chunk,
                        sequence: ++counter,
                        isLast: chunk.size < chunkSize ? true : false,
                        name: this.upload.chosen.name
                    });
                }
                this.socket.on('UPLOAD_FINISHED', () => {
                    this.progress = 100;
                    setTimeout(() => {
                        this.$swal({
                            title: 'Uploaded',
                            text: 'Ad has been uploaded successfully',
                            type: 'success',
                            confirmButtonColor: '#ff6500'
                        });
                        this.socket.disconnect();
                    },1000);
                });
                this.socket.on('UPLOAD_CHUNK_FINISHED', (data) => {
                    this.progress = (((data * 1000000) / this.upload.chosen.size) * 100).toFixed(0);
                });
                this.socket.on('UPLOAD_ERROR', () => {
                    this.$swal({
                        title: 'Error',
                        text: 'There was an error while uploading the video',
                        type: 'error'
                    });
                    this.socket.disconnect();
                });
            },

在后端:

let app = http.createServer();
    let io = socketIO(app, {
        origins: '*:*',
        wsEngine: 'ws',
        pingInterval: 10000,
        pingTimeout: 5000
    });
    app.listen(socketPort, () => {
        console.log('Socket started on port ' + socketPort);
    });
    io.on('connection', (socket) => {
        socket.on('UPLOAD_CHUNK', async (data) => {
            console.log('sent');
            let tempDir = './public/uploads/' + data.client + '/Temp';
            let extension = data.name.substr(data.name.lastIndexOf('.'));
            if (!fs.existsSync(tempDir)) {
                fs.mkdirSync(tempDir, {recursive: true});
            }
            let fd;
            try {
                fd = await fs.open(tempDir + '/' + Date.now() + extension, 'a', 0755);
            } catch (err) {
                logger.logError(err);
                socket.emit('UPLOAD_ERROR');
            }
            try {
                let result = await fs.write(fd, data.data, null, 'Binary');
                fs.close(fd);
            } catch (err) {
                logger.logError(err);
                socket.emit('UPLOAD_ERROR');
                return;
            }
            if (data.isLast) {
                let uploadDir = './public/uploads/' + data.client + '/Video/';
                if (!fs.existsSync(uploadDir)) {
                    fs.mkdirSync(uploadDir, {recursive: true});
                }
                let outputFile = fs.createWriteStream(path.join(uploadDir, Date.now() + extension));
                let filenames;
                try {
                    filenames = await fs.readdir(tempDir);
                } catch (err) {
                    logger.logError(err);
                    socket.emit('UPLOAD_ERROR');
                    return;
                }
                filenames.forEach(async(tempName) => {
                    const data = fs.readFileSync(`${tempDir}/${tempName}`);
                    try {
                        let result = await outputFile.write(data);
                    } catch (err) {
                        logger.logError(err);
                        socket.emit('UPLOAD_ERROR');
                        return;
                    }
                    try {
                        fs.removeSync(`${tempDir}/${tempName}`);
                    } catch (err) {
                        logger.logError(err);
                        socket.emit('UPLOAD_ERROR');
                    }
                });
                outputFile.end();
                outputFile.on('finish', async () => {
                    fs.removeSync(tempDir);
                    socket.emit('UPLOAD_FINISHED');
                });
            } else {
                socket.emit('UPLOAD_CHUNK_FINISHED', data.sequence);
            }
        });
    });

100%的使用量冻结了我的应用程序。我该如何调试此问题?

0 个答案:

没有答案