2014-10-08 65 views
0

我试图在第一台服务器关闭并试图重新连接失败时连接一台新服务器。 Upto现在工作正常,第一台服务器断开连接,第二台服务器连接并收听消息。开关插座服务器断开连接

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

@xhirase,请看看这个问题。预计你可以在这方面提供帮助。提前致谢。将尝试学习该网站的语言。 – 2014-10-08 08:50:11

+0

没有问题,这个网站是伟大的,所以我们都必须尽我们所能来保持这种方式。让我看看我能为你的问题做什么,现在它在正确的地方:) – xShirase 2014-10-08 08:55:38

回答

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) 

这应该给你的开关你的2台服务器之间的脱节,具有完全相同的属性和事件侦听器。当一个人崩溃时,另一个人接管。

+0

我还没有测试过,我不在我的电脑上。如果有错别字让我知道,但我想你会看到开关功能的重点 – xShirase 2014-10-08 09:16:30

+0

这真棒,你有良好的逻辑思维。谢谢你的想法。它正在工作...... @xshirase – 2014-10-08 10:28:17