Reconnection of Client when server reboots in WebSocket

后端 未结 9 2210
青春惊慌失措
青春惊慌失措 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:35

    I have been using this patten for a while for pure vanilla JavaScript, and it supports a few more cases than the other answers.

    document.addEventListener("DOMContentLoaded", function() {
    
      'use strict';
    
      var ws = null;
    
      function start(){
    
        ws = new WebSocket("ws://localhost/");
        ws.onopen = function(){
          console.log('connected!');
        };
        ws.onmessage = function(e){
          console.log(e.data);
        };
        ws.onclose = function(){
          console.log('closed!');
          //reconnect now
          check();
        };
    
      }
    
      function check(){
        if(!ws || ws.readyState == 3) start();
      }
    
      start();
    
      setInterval(check, 5000);
    
    
    });
    

    This will retry as soon as the server closes the connection, and it will check the connection to make sure it's up every 5 seconds also.

    So if the server is not up when this runs or at the time of the onclose event the connection will still come back once it's back online.

    NOTE: Using this script will not allow you to ever stop trying to open a connection... but I think that's what you want?

提交回复
热议问题