套接字IO重新连接?

disconnect连接后,如何重新连接到套接字io?

这是代码

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

如果我做的initSocket(true) ,它的作品。 如果我做initSocket(false) ,它断开连接。 但是,然后如果我尝试使用initSocket(true)重新连接,连接不再工作。 我怎样才能使连接工作?

那么,你有一个select在这里…

第一次初始化套接字值,你应该连接到io.connect

下次(在你断开一次连接之后),你应该连接到socket.socket.connect()

所以你的initSocket应该是这样的

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

我知道你已经有了一个答案,但我到了这里,因为socket.IO客户端重新连接function目前在节点中被破坏了。

github repo上的活动错误显示很多人在连接失败时没有收到事件,重新连接也不会自动发生。

要解决这个问题,可以创build一个手动重新连接循环,如下所示:

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

您可以通过以下客户端configuration重新连接。

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

我有一个与socket-io重新连接的问题。 可能是这种情况会帮助别人。 我有这样的代码:

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

这是错误的,因为在开放端口分配的callback之间存在延迟。 在DB初始化之前,一些消息可能会丢失。 解决这个问题的正确方法是:

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