Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js + socket.IO - socket not reconnecting?

I know socket.io has a built in feature for reconnecting and everything, however I don't think that it is working - as I have seen from others it's also not working for them either.

If a user puts their computer to sleep, it disconnects them, and then when they open it back up they are no longer connected so they don't any of the notifications or anything until they refresh the page. Perhaps it's just something that I'm not doing correctly?

var io = require('socket.io').listen(8080);
var users = {};

////////////////USER CONNECTED/////

console.log("Sever is now running");

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

    //Tell the client that they are connected
    socket.emit('connected');

    //Once the users session is recieved
    socket.on('session', function (session) {

        //Add users to users variable
        users[socket.id] = {userID:session, socketID:socket};

        //When user disconnects
        socket.on('disconnect', function () { 

        //socket.socket.connect();

             var count= 0;
            for(var key in users){
                if(users[key].userID==session)++count;
                if(count== 2) break;
            }
            if(count== 1){
               socket.broadcast.emit('disconnect', { data : session});
            }

            //Remove users session id from users variable
            delete users[socket.id];
        }); 


        socket.on('error', function (err) {
            //socket.socket.connect();
        });

socket.emit("connection") needs to be called when the user reconnects, or at least the events that happen in that event need to be called.

Also socket.socket.connect(); doesn't work, it returns with an error and it shuts the socket server down with an error of "connect doesn't exist".

like image 746
Dylan Cross Avatar asked Jan 13 '13 21:01

Dylan Cross


1 Answers

The problem is related to io.connect params.

Look at this client code (it will try to reconnect forever, with max delay between attempts 3sec):

 ioParams = {'reconnection limit': 3000, 'max reconnection attempts': Number.MAX_VALUE, 'connect timeout':7000}
 socketAddress = null
 socket = io.connect(socketAddress, ioParams)

There are two important parameters out there, related to your problem:

  • reconnection limit - limit the upper time of delay between reconnect attemts. Normally it's getting bigger and bigger in time of server outage
  • max reconnection attempts - how many times you want to try. Default is 10. In most cases this is the problem why the client stops trying.
like image 188
Luman75 Avatar answered Oct 28 '22 12:10

Luman75