Simon
Simon

Reputation: 504

Leaking sockets (sockets.io)

I have a client that connects to a socket server (node.js). I seem to being leaking sockets.

Here is the flow that causes the leaked sockets.

  1. Connect to socket server
  2. Signout (I see the log out confirmation on the server)
  3. Signin in again to the socket server (see confirmation on socket server)
  4. Restart socket server quickly (force restart using supervisor module by resaving a file)
  5. Client reconnects to socket server. I now see 2 sockets that have connected to the socket server, instead of what should be just one.

If I repeat steps 2-4, I can see multiple connections from the same client.

Here is my client socket.io code:

client.js:

function start_socket(tok){
    console.log("socket trying to connect");
    //try every second to reconnect        
    socket = io.connect(sockets_host, { query: $.param({token: tok}), 'forceNew' : true, 'reconnection limit' : 100, 'max reconnection attempts' : 'Infinity' });

    socket.on('connect', function() {
            console.log('connected to socket server');
            set_loggedin_status('true');
    });
    socket.on('disconnect', function() {
            console.log('disconnected from server');
            set_loggedin_status('false');
            close_socket(); //get leaked sockets, wether I call this or not, though less if I do...
    });
    socket.on('error',function(err){
            console.log('socket error: ' + err);
            attempt_login();
    });
}

function close_socket(){
    console.log("in close socket");
    socket.disconnect(true);
    set_loggedin_status('false');
}

I've tried the above without 'forceNew' : true,, but then I seem to have problems signing in again after the client signed-out.

If I call close_socket from within the disconnected event (and not just from elsewhere when the client chooses to signout), I seem to get fewer leaked sockets, but still get them.

How am I creating multiple sockets?

Upvotes: 1

Views: 535

Answers (1)

Simon
Simon

Reputation: 504

The solution, though not necessarily the answer to the question, was in my case to use socket.io.disconnect() instead of socket.disconnect().

However, this meant if the socket server goes down once i've already established a connection, that no reconnects were being tried. So, I have to handle this situation myself if using this approach to solve the leaking sockets.

Upvotes: 0

Related Questions