Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS + Socket.io connections dropping/reconnecting?

In production, I have a game which uses connection-local variables to hold game state. However I notice that if I idle for a certain time on the connection, it disconnects and reconnects which loses the current state. During my tests on a local host, I never noticed this behavior. Is this the norm behavior for socket connections or is something else causing the connections to drop.

If it is a normal behavior how is this typically handled? Should connection values be stored globally so they can be restored should a user drop/reconnect?

like image 206
majic bunnie Avatar asked Mar 14 '12 19:03

majic bunnie


1 Answers

Your problem is around socket timeouts. If there's no activity on a certain socket, socket.io will close it automatically.

An easy (and hackish) fix is to send a heartbeat to the connected client to create activity and stop the socket from timing out.

Server:

function sendHeartbeat(){
    setTimeout(sendHeartbeat, 8000);
    io.sockets.emit('ping', { beat : 1 });
}

io.sockets.on('connection', function (socket) {
    socket.on('pong', function(data){
        console.log("Pong received from client");
    });
}

setTimeout(sendHeartbeat, 8000);

Client:

socket.on('ping', function(data){
      socket.emit('pong', {beat: 1});
    });

More Information:

You can get more information on configuring socket.io here.

EDIT: Mark commented that if the user does lose the connection (connection drops on his end because of internet troubles), you should be able to restore the user to his last state.

To do that, the best way would be to use a already widely used method for storing user data, cookies and sessions.

An extremely well done tutorial on how to do this located here. Although he uses express to set cookies, you can do this using anything (I do it using rails). Using this method, you can store the user data in a cookie and fetch it during the handshake. From there you can just access the data using socket.handshake.data.

like image 197
Moox Avatar answered Nov 15 '22 16:11

Moox