套接字IO重新连接? [英] Socket IO reconnect?

查看:153
本文介绍了套接字IO重新连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一旦调用了 disconnect ,如何重新连接到套接字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(是的),它有效。如果我执行 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,

下一次(在你断开一次断开连接之后),你应该用 socket.socket.connect()连接回来。

The next time ( after you've called disconnect once ), you should connect back with 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
    }
} 

这篇关于套接字IO重新连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆