Javascript 套接字 IO 重新连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10437584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:19:02  来源:igfitidea点击:

Socket IO reconnect?

javascriptnode.jssocket.io

提问by Eric

How to reconnect to socket io once disconnecthas been called?

一旦disconnect被调用,如何重新连接到socket io ?

Here's the code

这是代码

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

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?

如果我这样做initSocket(true),它的工作原理。如果我这样做initSocket(false),它会断开连接。但是,如果我尝试使用 重新连接initSocket(true),则连接不再起作用。我怎样才能使连接正常工作?

回答by drinchev

Well, you have an option here ...

好吧,你在这里有一个选择......

The first time you initialize the socket value you should connect with io.connect,

第一次初始化应该连接的套接字值时io.connect

The next time ( after you've called disconnect once ), you should connect back with socket.socket.connect().

下一次(在您调用了 disconnect 一次之后),您应该使用socket.socket.connect().

So your initSocket, should be something like

所以你的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
    }
} 

回答by Matthew F. Robben

I know you already have an answer, but I arrived here because the socket.IO client reconnection feature is broken in node at the moment.

我知道您已经有了答案,但我来到这里是因为目前 node 中的 socket.IO 客户端重新连接功能已损坏。

Active bugs on the github repo show that lots of people aren't getting events on connect failure, and reconnect isn't happening automatically.

github repo 上的活跃错误表明,很多人没有收到连接失败的事件,并且重新连接不会自动发生。

To work around this, you can create a manual reconnect loop as follows:

要解决此问题,您可以创建手动重新连接循环,如下所示:

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

回答by Prasad Bhosale

You can reconnect by following client side config.

您可以按照客户端配置重新连接。

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

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

回答by Aldo

This is an old question, but I was struggling with this recently and stumbled here. Most recent versions of socket.io (>2.0) doesn't have the socket.socketproperty anymore as pointed out here.

这是一个老问题,但我最近一直在努力解决这个问题,并在这里绊倒了。最新版本的 socket.io (>2.0) 不再具有这里socket.socket指出的属性。

I am using socket.io-client 2.2.0and I was facing a situation where the socket seems to be connected (property socket.connected = true) but it wasn't communicating with the server.

我正在使用socket.io-client 2.2.0,但我遇到了套接字似乎已连接(属性socket.connected = true)但未与服务器通信的情况。

So, to fix that, my solution was call socket.close()and socket.open. These commands force a disconnection and a new connection.

所以,为了解决这个问题,我的解决方案是调用socket.close()socket.open。这些命令强制断开连接并建立新连接。

回答by Stepan Yakovenko

I had an issue with socket-io reconnect. May be this case will help someone. I had code like this:

我遇到了 socket-io 重新连接的问题。可能这种情况会帮助某人。我有这样的代码:

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

this is wrong, becase there is a delay between open port assigned callbacks. Some of messages may be lost before DB gets initialized. The right way to fix it is:

这是错误的,因为开放端口分配的回调之间存在延迟。在数据库初始化之前,某些消息可能会丢失。正确的修复方法是:

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