49

How to reconnect to socket io once disconnect has been called?

Here's the code

function initSocket(__bool){                    
    if(__bool == true){             
        socket = io.connect('http://xxx.xxx.xxx.xxx:8081', {secure:false});     
        socket.on('connect', function(){console.log('connected')});                                 
        socket.on('disconnect', function (){console.log('disconnected')});
    }else{
        socket.disconnect();
        socket = null;
    }
}   

If I do initSocket(true), it works. If I do initSocket(false), it disconnects. BUT THEN if I try to reconnect using initSocket(true), the connection does not work anymore. How can I get the connection to work?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Eric
  • 9,870
  • 14
  • 66
  • 102
  • 1
    It's built into the library. See http://stackoverflow.com/a/5149185/17803 – Matt May 03 '12 at 18:53
  • possible duplicate of [Node.js and Socket.IO - How to reconnect as soon as disconnect happens](http://stackoverflow.com/questions/4432271/node-js-and-socket-io-how-to-reconnect-as-soon-as-disconnect-happens) – Matt May 03 '12 at 18:54
  • 7
    I don't want it to reconnect on disconnect ! i want to be able to control when to connect and disconnect.. – Eric May 03 '12 at 18:55
  • The web app is loaded with stuff so depending on what's going on, i want to disconnect, then reconnect when a user clicks something for exemple.. – Eric May 03 '12 at 18:56
  • Ah, I see. So, um, why? Isn't the purpose of a websocket to persist and avoid these connect/disconnect overheads? – Matt May 03 '12 at 19:03
  • 7
    It's just a socket connection, i should be able to connect and disconnect whenever i want :) – Eric May 03 '12 at 19:04
  • What exactly happens when you call initSocket(true) for the second time? Any errors? On the websocket server, do you see any connection attempts? – Matt May 03 '12 at 19:06
  • +1 I have the same question. My code is different but I'm trying to do the same thing. No JS errors. No connection attempt on the server. io.connect() seems to die silently when called a second time. Very frustrating. – Andrew Ensley May 23 '12 at 21:26

5 Answers5

53

Well, you have an option here ...

The first time you initialize the socket value you should connect with io.connect,

The next time ( after you've called disconnect once ), you should connect back with socket.socket.connect().

So your initSocket, should be something like

function initSocket(__bool){                    
    if(__bool){          
        if ( !socket ) {   
            socket = io.connect('http://xxx.xxx.xxx.xxx:8081', {secure:false});     
            socket.on('connect', function(){console.log('connected')});                                 
            socket.on('disconnect', function (){console.log('disconnected')});
        } else {
            socket.socket.connect(); // Yep, socket.socket ( 2 times )
        }
    }else{
        socket.disconnect();
        // socket = null; <<< We don't need this anymore
    }
} 
Pir Shukarullah Shah
  • 4,124
  • 2
  • 22
  • 42
drinchev
  • 19,201
  • 4
  • 67
  • 93
16

I know you already have an answer, but I arrived here because the socket.IO client reconnection feature is broken in node at the moment.

Active bugs on the github repo show that lots of people aren't getting events on connect failure, and reconnect isn't happening automatically.

To work around this, you can create a manual reconnect loop as follows:

var socketClient = socketioClient.connect(socketHost)

var tryReconnect = function(){

    if (socketClient.socket.connected === false &&
        socketClient.socket.connecting === false) {
        // use a connect() or reconnect() here if you want
        socketClient.socket.connect()
   }
}

var intervalID = setInterval(tryReconnect, 2000)

socketClient.on('connect', function () {
    // once client connects, clear the reconnection interval function
    clearInterval(intervalID)
    //... do other stuff
})
Matthew F. Robben
  • 1,906
  • 1
  • 12
  • 6
  • Note that this answer does *not* answer the OP's question (who wants to reconnect manually), and (in my experience) socket.io auto reconnection works well now. – user202729 Jan 22 '20 at 04:46
5

You can reconnect by following client side config.

// 0.9  socket.io version
io.connect(SERVER_IP,{'force new connection':true });

// 1.0 socket.io version
io.connect(SERVER_IP,{'forceNew':true });
Prasad Bhosale
  • 682
  • 8
  • 20
  • 8
    I don't think `forceNew` means reconnect. I believe it means to create a new socket each time this statement is called because normally `io.connect()` will return the same socket if you call it a second time. – Thalis K. Jun 28 '15 at 21:18
2

This is an old question, but I was struggling with this recently and stumbled here. Most recent versions of socket.io (>2.0) doesn't have the socket.socket property anymore as pointed out here.

I am using socket.io-client 2.2.0 and I was facing a situation where the socket seems to be connected (property socket.connected = true) but it wasn't communicating with the server.

So, to fix that, my solution was call socket.close()and socket.open. These commands force a disconnection and a new connection.

Aldo
  • 1,199
  • 12
  • 19
0

I had an issue with socket-io reconnect. May be this case will help someone. I had code like this:

var io = require('socket.io').listen(8080);
DB.connect(function () {
    io.sockets.on('connection', function (socket) {
        initSockets(socket);
    });
});

this is wrong, becase there is a delay between open port assigned callbacks. Some of messages may be lost before DB gets initialized. The right way to fix it is:

var io = null;
DB.connect(function () {
    io = require('socket.io').listen(8080);
    io.sockets.on('connection', function (socket) {
        console.log("On connection");
        initSockets(socket);
    });
});
Stepan Yakovenko
  • 8,670
  • 28
  • 113
  • 206