¿Socket IO reconectar?

How to reconnect to socket io once disconnect ¿ha sido llamado?

Aqui esta el codigo

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;
    }
}   

Si lo hago 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?

preguntado el 03 de mayo de 12 a las 19:05

It's built into the library. See stackoverflow.com/a/5149185/17803 -

I don't want it to reconnect on disconnect ! i want to be able to control when to connect and disconnect.. -

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.. -

It's just a socket connection, i should be able to connect and disconnect whenever i want :) -

5 Respuestas

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().

Entonces tus 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
    }
} 

respondido 23 nov., 17:18

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
})

respondido 29 nov., 12:15

Tenga en cuenta que esta respuesta no no answer the OP's question (who wants to reconnect manually), and (in my experience) socket.io auto reconnection works well now. - user202729

Puede volver a conectarse siguiendo la configuración del lado del cliente.

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

// 1.0 socket.io version
io.connect(SERVER_IP,{'forceNew':true });

Respondido el 04 de diciembre de 14 a las 05:12

No creo que 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.

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 aquí.

Estoy utilizando 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()y socket.open. These commands force a disconnection and a new connection.

contestado el 17 de mayo de 19 a las 12:05

This is a working solution for the latest version of socket.io, confirming for version 4.4.0. - amrendra

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);
    });
});

Respondido 07 Oct 15, 16:10

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.