2014-10-08 115 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

相關問題