Ale
Ale

Reputation: 23

Socket.io doesn't close connections when users close browser

I have a socket server (socket.io + nodejs) and a socket client (socket.io). The problem is that client connections remain opened also when users close the browser, creating an high number of dead connections.

For example, when I open the browser and run this command "lsof -i -n -P | grep node | grep ‘my ip address’" I have one connection. When I close the browser and run again that command, the connection remains opened.

Thanks a lot everyone wants to help me!

Upvotes: 2

Views: 5373

Answers (2)

num8er
num8er

Reputation: 19372

Make ping-pong feature where server will broadcast ping event, and client-side must response with pong.
If during 10 seconds (in this example) server will not get pong event so garbage cleaner function will disconnect socket.

Server-side:

var aliveSockets = {};

// broadcasting ping
setInterval(function() {
  io.emit('ping', {timestamp: (new Date()).getTime()});
}, 10000); // 10 seconds

// cleaning up stalled socket which does not answer to ping
setInterval(function() {
  aliveSockets.forEach(function(aliveSocket, idx) {
    if(!aliveSocket) {return;}
    if(aliveSocket.lastPong + 10 < (new Date().getTime())/1000) {
      aliveSocket.socket.disconnect(0);
      delete aliveSocket[idx];
    }
  });
}, 1000); // 1 second

io.on('connection', function(socket) {
  sockets[socket.id] = socket;

  socket.on('pong', function() {
    aliveSockets[socket.id] = {socket: socket, lastPong: ((new Date()).getTime()/1000)};
  });
});

Client-side:

io.on('ping', function() {
  io.emit('pong', {timestamp: (new Date()).getTime()});
});

p.s. idea is just workaround, but I do prefer not to write ping-pong-ers, just trust to socket.io library, it will remove it after some time (~1 minute)

read this: https://github.com/socketio/engine.io#methods-1 You can see it has pingTimeout that means socket.io will handle Your problem automatically.

pingTimeout (Number): how many ms without a pong packet to consider the connection closed (60000)

Upvotes: 1

Siddhartha Chowdhury
Siddhartha Chowdhury

Reputation: 2732

Try using socket.disconnect()on the client side, this should work.

Connection shouldnt be on once either the server or client triggers disconnect. There must be some other issue in your code on the server side. Try using this to close connection on the server side

socket.on('terminate', function (){
    socket.disconnect(0);
});

And this on the client side:

var io = io();
io.emit('terminate');

See if it works out for you. Thanks

Upvotes: 1

Related Questions