简体   繁体   中英

second io.connection() in socket.io does not fire connect event

I need to dyanmically change the server to which the client connects. So, in my case the client if first connect to a server with:

var $socket = io.connect("//serverA:5656");

and this successfully fires the event code:

$socket.on('connect', function(data) {
   alert('socket connected with id ' + $socket.id);
});

however, if later on the code I need to change the server to connect to with:

$socket = io.connect("//serverB:8900");

the connect event is not fired even though it seems to generate a new value for $socket.id but any emit from server to this socket does not go through.

I tried with several options for the new server connection such as:

$socket.disconnect(true);
$socket = io.connect("//serverB:8900");
$socket.io.reconnect();

$socket.disconnect();
$socket.removeAllListeners('connect');
io.sockets = {};
$socket = io.connect("//serverB:8900");

$socket = io.connect("//serverB:8900", {'forceNew': true});

$socket = io.connect("//serverB:8900", {'force new connection': true});

None of this (and any combination of them) worked out.

io.connect creates a new socket object. You create your first socket object when you call io.connect("//serverA:5656") . Then, you set a connect event listener on that socket.

You create a totally new socket when you call io.connect("//serverB:8900") . This new socket object doesn't know anything about the first socket you made previously. Importantly, it does not have a connect event listener.

You need to call .on('connect', ...) again, on the second socket object, to make it have a connection listener as well. Generally, every time you call io.connection , you need to make a subsequent call to on to attack a connection listener. You can put this operation in a single function to make it easier:

function makeSocketWithListener(server) {
    var socket = io.connect(server);
    socket.on("connect", function() {
        alert('socket connected with id ' + socket.id);
    });
    return socket;
}

var $socket = makeSocketWithListener("//serverA:5656");

...

var $socket = makeSocketWithListener("//serverB:8900");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM