socket.io内存泄漏的问题
发布于 18小时前 作者 alonprince 68 次浏览 来自 问答

我写了一个socket.io的demo,想用websocket-bench来测试一下socket的并发量和最大连接数,结果发现测试结束后,所有socket都与服务器断开连接了,但是内存好像没有释放掉,不知道是我代码写的有问题还是有哪些使用socket的过程中需要注意的我没注意。

'use strict'

var app = require('koa')();
var serve = require('koa-static');
var _ = require('underscore');
var config = require('../config.js');

var n = 0;
const port = process.env.PORT || 3000;

var clients = {};

var clientCache = [];

for(let i = 100000; i <= config.n; i++) {
    clientCache.push(i);
}

clientCache = _.shuffle(clientCache);


app.use(serve('.'));

var server = require('http').Server(app.callback()),
    io = require('socket.io')(server);

io.on('connection', function(socket) {

    let randomNumber = clientCache.pop();
    let total = 0;

    clients[randomNumber] = socket;
    console.log(`new customer come, total: ${++n}`);

    socket.emit('server', {
        server: 'Server1',
        port: port
    });

    socket.on('msg', (data) => console.log(`收到${++total}条消息,耗时${new Date() - new Date(data.dateTime)}ms`));

    socket.on('error', (err) => console.log(err, 11));

    socket.on('disconnect', function(socket) {
        console.log(`delete customer, total: ${--n}`);
        delete clients[randomNumber];
    })
})

server.listen(port, () => console.log('listening on : ' + port));

例如我连接10000个,可能内存就到1.7G了,结束掉websocket-bench进程后,1.7G的内存一点都没释放掉

回到顶部