首页 文章

断开连接时切换套接字服

提问于
浏览
0

我试图在第一台服务器关闭并尝试reconnect_failed时连接新服务器 . 到目前为止它工作正常,第一台服务器断开连接,第二台服务器连接并收听消息 .

socket.on('reconnect_failed', function () {
    console.log("reconnect_failed");
    socket = io.connect('http://localhost:4000',{
            'reconnectionDelay': 100,
            'reconnect':false,
            'reconnectionAttempts': max_reconnects});
    console.log(socket);
});

socket.on('new message', function(msg){
    console.log(msg);
    document.getElementById("chat").innerHTML = msg;
});

但在客户端,第二台服务器不会监听“新消息”事件 . 由于该套接字在重新连接内启动失败 . 有没有其他方法可以用更少的代码进行处理 .

1 回答

  • 1

    我要做的是有一个断开连接时切换服务器的功能 . 就像是 :

    function initSocket(i){
       sockets = io.connect(servers[i], {
                'reconnectionDelay': 100,
                'reconnect':false,
                'reconnectionAttempts': max_reconnects});
       sockets.on("connection", function(socket){
           socket.on('connect',function(data){});
    
           socket.on('new message', function(msg){
               console.log(msg);
               document.getElementById("chat").innerHTML = msg;
           });
    
           socket.on('reconnect_failed', function () {
               console.log("reconnect_failed");
               i==0 ? 1 : 0; //switch the value of i
               initSocket(i) //init a socket on the other server
           });
       });
    }
    
    var servers = ["http://localhost:3000","http://localhost:4000"];
    
    initSocket(0); //start with server 0 (http://localhost:3000)
    

    这应该允许您在断开连接的两个服务器之间切换,具有完全相同的属性和事件侦听器 . 当一个人崩溃时,另一个人接管 .

相关问题