Socket.io: How to handle closing connections?

2019-02-03 02:37发布

I'm trying to understand which are the "physical" limits of my application.

On the client side:

var socket = io.connect("http://127.0.0.1:6701");
socket.on('connect', function() {
  socket.disconnect();
});
socket.on('disconnect', function() {
  socket.socket.reconnect();
});

On the server side:

var io = require('socket.io').listen(6701);

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

  socket.on('disconnect', function(reason) {
    var o = Object.keys(socket.manager.open).length
      , c = Object.keys(socket.manager.closed).length
      , cA = Object.keys(socket.manager.closedA).length
      , h = Object.keys(socket.manager.handshaken).length

      console.log("open: " + o)
      console.log("closed: " + c)
      console.log("handshaken: " + h)
      console.log("closedA: " + cA)
      console.log("---");
   });
});

When in OSX I hit the file limit (256) the statistics are the following

open: 471
closed: 235
handshaken: 471
closedA: 235

What is puzzling me is:

  • if I forcefully close the connection (this is what I would like to do with the client disconnect(), why I'm still using a file handle (so I hit the file limit) edit: adding a delay seems that the server can keep breath and never reaches the file limit)?
  • Is there a way to completely close the socket so I could be pretty sure the file limit is rarely reached (I know that I can push it to 65K)?
  • Is there a way to know that I'm reaching the file limit, so that I can stop accepting connection?

Thank you

1条回答
Viruses.
2楼-- · 2019-02-03 03:01

It's better if client sends a "terminate" command to server which then closes the connection, than the other way around.

Server will always wait until a timeout before giving up on a connection. Even if that timeout is small, with loads of connections coming in, it will overload it. That's why, for example, is always good to disable keep-alive on app servers.

Delay helps because server has time to close the connection before opening a new one.

查看更多
登录 后发表回答