套接字 IO 重新连接? [英] Socket IO reconnect?
问题描述
一旦disconnect
被调用,如何重新连接到socket io?
How to reconnect to socket io once disconnect
has been called?
这是代码
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)
重新连接,连接将不再起作用.我如何才能使连接正常工作?
If I do 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?
推荐答案
好吧,这里有一个选项......
Well, you have an option here ...
第一次初始化套接字值时应该使用io.connect
,
The first time you initialize the socket value you should connect with io.connect
,
下一次(在您调用了 disconnect 一次之后),您应该使用 socket.socket.connect()
重新连接.
The next time ( after you've called disconnect once ), you should connect back with socket.socket.connect()
.
所以你的 initSocket
应该类似于
So your 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
}
}
这篇关于套接字 IO 重新连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!