Socket IO infinite loop over 1000 connections

时间:2015-06-30 13:58:05

标签: node.js socket.io ulimit

I need to benchmark multiples socket connections. I've got a nodejs server with this following code :

var io = require('./lib/node_modules/socket.io').listen(12345)

io.sockets.on("connect", function(socket) {
    console.log("Socket " + socket.id + " connected.")

    socket.on("disconnect", function() {
        console.log("Socket " + socket.id +" disconnected.")
    })
})

and a nodejs client :

var port            = 12345
,   nbSocket        = 1000
,   io              = require("./lib/node_modules/socket.io-client")

for (var i = 1;i <= nbSocket;i++)
{
    var socket = io.connect("http://<<my_ip>>:" + port, {forceNew: true})
}

When client code was executed, server correctly connects sockets and ends normally.

But if we change nbSocket to 2000, server never ends connecting and disconnecting sockets.

We already tried to change the limit with :

ulimit -n5000

But it didn't worked. Is there another limit somewhere or something we missed ?

1 个答案:

答案 0 :(得分:1)

我在运行Node v0.12.4和socket.io v1.3.5的OSX上进行了测试,它开始引起我nbSocket=5000周围的问题。

尝试将此代码段附加到服务器脚本的末尾:

process.on('uncaughtException', function(err) {
    console.info(util.inspect(err, {colors: true}));
});

另外,我稍微更改了你的代码并添加了一个计时器,每秒两次打印开放套接字的数量:

var
    util = require('util'),
    io = require('socket.io').listen(12345);

var
    clientCount = 0;

function onClientDisconnect() {
    clientCount--;
}

io.on('connect', function(socket) {
    clientCount++;
    socket.on('disconnect', onClientDisconnect);
});

console.info('Listening...');

setInterval(function () {
    console.info('Number of open sockets: %d', clientCount);
}, 500);

process.on('uncaughtException', function(err) {
    console.info(util.inspect(err, {colors: true}));
});

当开放套接字的数量开始接近5000时,我开始多次看到这两条消息:

{ [Error: accept ENFILE] code: 'ENFILE', errno: 'ENFILE', syscall: 'accept' }
{ [Error: accept EMFILE] code: 'EMFILE', errno: 'EMFILE', syscall: 'accept' }

根据libc manual

  • ENFILE:整个系统中有太多不同的文件开放
  • EMFILE:当前进程打开的文件太多

所以实际上我的问题是文件描述符的限制,因此通过将上述代码段附加到服务器脚本来检查它是否也是您的问题。如果出现例外情况,您应该调查如何properly increase the limit of open files in your system