Reconnection of Client when server reboots in WebSocket

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

    function wsConnection(url){
        var ws = new WebSocket(url);
        var s = (l)=>console.log(l);
    	ws.onopen = m=>s(" CONNECTED")
        ws.onmessage = m=>s(" RECEIVED: "+JSON.parse(m.data))
        ws.onerror = e=>s(" ERROR")
        ws.onclose = e=>{
            s(" CONNECTION CLOSED");
            setTimeout((function() {
                var ws2 = new WebSocket(ws.url);
    			ws2.onopen=ws.onopen;
                ws2.onmessage = ws.onmessage;
                ws2.onclose = ws.onclose;
                ws2.onerror = ws.onerror;
                ws = ws2
            }
            ).bind(this), 5000)
        }
        var f = m=>ws.send(JSON.stringify(m)) || "Sent: "+m;
        f.ping = ()=>ws.send(JSON.stringify("ping"));
        f.close = ()=>ws.close();
        return f
    }
    
    c=new wsConnection('wss://echo.websocket.org');
    setTimeout(()=>c("Hello world...orld...orld..orld...d"),5000);
    setTimeout(()=>c.close(),10000);
    setTimeout(()=>c("I am still alive!"),20000);
    <pre>
    This code will create a websocket which will 
    reconnect automatically after 5 seconds from disconnection.
    
    An automatic disconnection is simulated after 10 seconds.

    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2020-12-02 05:38

    Can't comment, but the following:

    var socket;
    
    const socketMessageListener = (event) => {
      console.log(event.data);
    };
    
    const socketOpenListener = (event) => {
      console.log('Connected');
      socket.send('hello');
    };
    
    const socketCloseListener = (event) => {
      if (socket) {
        console.error('Disconnected.');
      }
      socket = new WebSocket('ws://localhost:8080');
      socket.addEventListener('open', socketOpenListener);
      socket.addEventListener('message', socketMessageListener);
      socket.addEventListener('close', socketCloseListener);
    };
    
    socketCloseListener();
    
    // for testing
    setTimeout(()=>{
      socket.close();
    },5000);
    

    Plus https://www.npmjs.com/package/back is already good enough :)

    0 讨论(0)
  • 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 */
     /* ... */
    }
    
    0 讨论(0)
  • 2020-12-02 05:46

    The client side close event for WebSocket has a wasClean property, which was useful to me. Seems like it is set to true in cases where the client computer goes into sleep mode etc. or when the server is unexpectedly stopped etc. It is set to false if you manually close the socket, in which case you don't want to open the socket automatically again. Below code from an Angular 7 project. I have this code in a service, so it is usable from any component.

        notifySocketClose(event) { 
    
            if (!event.wasClean) { 
                setTimeout(() => {
                    this.setupSocket()
                }, 1000);       
            }
        }
    
        setupSocket() { // my function to handle opening of socket, event binding etc.
        .....
        .....
    
                this.websocketConnection = this.websocketConnection ? this.websocketConnection : new WebSocket(socketUrl);
                this.websocketConnection.onclose = this.notifySocketClose.bind(this);   
            } 
        }
        .....
        .....
    
    
    0 讨论(0)
  • 2020-12-02 05:47

    When the server reboots, the Web Socket connection is closed, so the JavaScript onclose event is triggered. Here's an example that tries to reconnect every five seconds.

    function start(websocketServerLocation){
        ws = new WebSocket(websocketServerLocation);
        ws.onmessage = function(evt) { alert('message received'); };
        ws.onclose = function(){
            // Try to reconnect in 5 seconds
            setTimeout(function(){start(websocketServerLocation)}, 5000);
        };
    }
    
    0 讨论(0)
提交回复
热议问题