[英]Socket IO reconnect?
一旦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)
重新连接initSocket(true)
,则连接不再起作用。 如何才能使连接正常工作?
嗯,你有一个选择......
第一次初始化套接字值时,应该连接io.connect
,
下一次(在您调用disconnect之后),您应该使用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客户端重新连接功能此时在节点中被破坏了。
github repo上的活动错误表明很多人没有在连接失败时获得事件,并且没有自动重新连接。
要解决此问题,您可以创建手动重新连接循环,如下所示:
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
})
您可以通过以下客户端配置重新连接。
// 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(> 2.0)不再具有socket.socket
属性,如此处所述 。
我正在使用socket.io-client 2.2.0
,我正面临套接字似乎已连接的情况(属性socket.connected = true
),但它没有与服务器通信。
所以,为了解决这个问题,我的解决方案是调用socket.close()
和socket.open
。 这些命令强制断开连接和新连接。
我有socket-io重新连接的问题。 可能这种情况会对某人有所帮助。 我有这样的代码:
var io = require('socket.io').listen(8080);
DB.connect(function () {
io.sockets.on('connection', function (socket) {
initSockets(socket);
});
});
这是错误的,因为开放端口分配的回调之间存在延迟。 在初始化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);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.