Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NodeJS + Socket.io connections dropping/reconnecting?

NodeJS + Socket.io connections dropping/reconnecting?

Problem

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?

Problem courtesy of: majic bunnie

Solution

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.

Solution courtesy of: Moox

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

NodeJS + Socket.io connections dropping/reconnecting?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×