套接字IO重新连接?

Eri*_*ric 36 javascript node.js socket.io

如何重新连接socket io一次disconnect被调用?

这是代码

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;
    }
}   
Run Code Online (Sandbox Code Playgroud)

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

dri*_*hev 45

嗯,你有一个选择......

第一次初始化应该连接的套接字值时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
    }
} 
Run Code Online (Sandbox Code Playgroud)


Mat*_*ben 14

我知道你已经有了答案,但我到了这里是因为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
})
Run Code Online (Sandbox Code Playgroud)


Pra*_*ale 6

您可以通过以下客户端配置重新连接.

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

// 1.0 socket.io version
io.connect(SERVER_IP,{'forceNew':true });
Run Code Online (Sandbox Code Playgroud)

  • 我不认为`forceNew`意味着重新连接.我相信这意味着每次调用此语句时都会创建一个新的套接字,因为如果你第二次调用它,通常`io.connect()`将返回相同的套接字. (5认同)