Reconnection of Client when server reboots in WebSocket

后端 未结 9 2231
青春惊慌失措
青春惊慌失措 2020-12-02 05:03

I am using web socket using PHP5 and the Chrome browser as client. I have taken the code from the site http://code.google.com/p/phpwebsocket/.

I run the server, and

9条回答
  •  独厮守ぢ
    2020-12-02 05:42

    The solution given by Andrew isn't perfectly working because, in case of lost connection, the server might send several close events.

    In that case, you'll set several setTimout's. The solution given by Andrew may only work if the server is ready before five seconds.

    Then, based on Andrew solution, reworked, I've made use of setInterval attaching the ID to the window object (that way it is available "everywhere"):

    var timerID=0;
    
    var socket;
    
    /* Initiate what has to be done */
    
    socket.onopen=function(event){
     /* As what was before */
     if(window.timerID){ /* a setInterval has been fired */
       window.clearInterval(window.timerID);
       window.timerID=0;
     }
     /* ... */
    }
    
    socket.onclose=function(event){
      /* ... */
     if(!window.timerID){ /* Avoid firing a new setInterval, after one has been done */
      window.timerID=setInterval(function(){start(websocketServerLocation)}, 5000);
     }
     /* That way, setInterval will be fired only once after losing connection */
     /* ... */
    }
    

提交回复
热议问题