简体   繁体   English

socket.io中的第二个io.connection()不会触发连接事件

[英]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. 即使它似乎为$ socket.id生成了一个新值,也不会触发connect事件,但是从服务器到此套接字的任何发射都不会通过。

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. io.connect创建一个新的套接字对象。 You create your first socket object when you call io.connect("//serverA:5656") . 调用io.connect("//serverA:5656")时,将创建第一个套接字对象。 Then, you set a connect event listener on that socket. 然后,在该套接字上设置一个connect事件侦听器。

You create a totally new socket when you call io.connect("//serverB:8900") . 当您调用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. 重要的是,它没有connect事件监听器。

You need to call .on('connect', ...) again, on the second socket object, to make it have a connection listener as well. 您需要在第二个套接字对象上再次调用.on('connect', ...) ,以使其也具有connection侦听器。 Generally, every time you call io.connection , you need to make a subsequent call to on to attack a connection listener. 通常,每次调用io.connection ,都需要随后调用on来攻击connection侦听器。 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(“ // serverA:5656”);

... ...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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