Continuous automatic reconnection of EventSource

I am using JavaScript EventSource in my project interface.

Sometimes the connection between the browser and the server fails or the server crashes. In these cases, EventSource attempts to connect after 3 seconds, as described in the documentation.

But he tries only once. If the connection is still unavailable, EventSource stops trying to reconnect, and the user must refresh the browser window in order to reconnect.

How can I prevent this behavior? I need an EventSource to try reconnecting forever, not just once.

Firefox Browser.

+4
source share
3 answers

, keep-alive; , , , , -.

(Blatant plug, O'Reilly : HTML5 SSE), , - , , , , 30 . , EventSource . : , , . , , 30 , .

, :

var keepAliveTimer = null;

function gotActivity(){
  if(keepaliveTimer != null)clearTimeout(keepaliveTimer);
  keepaliveTimer = setTimeout(connect, 30 * 1000);
}

function connect(){
  gotActivity();
  var es = new EventSource("/somewhere/");
  es.addEventListener('message', function(e){
    gotActivity();
    },false);
}
...
connect();

, getActivity() . , , - , .

, , ( "" ) 25-30 . , . , , , 25-30 .

Event-Last-Id, , keep-alive ; .

+5

, , , , HTTP- (, 500).

- : reconnecting-eventsource. , .

0

, , .

debounce . . 1 , 4, 8, 16... 64 , .

function isFunction(functionToCheck) {
  return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}

function debounce(func, wait) {
    var timeout;
    var waitFunc;

    return function() {
        if (isFunction(wait)) {
            waitFunc = wait;
        }
        else {
            waitFunc = function() { return wait };
        }

        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            func.apply(context, args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, waitFunc());
    };
}

// reconnectFrequencySeconds doubles every retry
var reconnectFrequencySeconds = 1;
var evtSource;

var reconnectFunc = debounce(function() {
    setupEventSource();
    // Double every attempt to avoid overwhelming server
    reconnectFrequencySeconds *= 2;
    // Max out at ~1 minute as a compromise between user experience and server load
    if (reconnectFrequencySeconds >= 64) {
        reconnectFrequencySeconds = 64;
    }
}, function() { return reconnectFrequencySeconds * 1000 });

function setupEventSource() {
    evtSource = new EventSource(/* URL here */); 
    evtSource.onmessage = function(e) {
      // Handle even here
    };
    evtSource.onopen = function(e) {
      // Reset reconnect frequency upon successful connection
      reconnectFrequencySeconds = 1;
    };
    evtSource.onerror = function(e) {
      evtSource.close();
      reconnectFunc();
    };
}
setupEventSource();
0

Source: https://habr.com/ru/post/1527321/


All Articles