Is an EventSource (SSE) supposed to try to reconnect indefinitely?

前端 未结 6 1988
余生分开走
余生分开走 2021-01-30 09:22

I\'m working on a project utilizing Server-Sent-Events and have just run into something interesting: connection loss is handled differently between Chrome and Firefox.

O

6条回答
  •  生来不讨喜
    2021-01-30 09:52

    I rewrote the solution of @Wade and after a little bit of testing I came to the conclusion that the functionality stayed the same with less code and better readability (imo). However I am still a beginner and I would love to get feedback from you. I am not sure if I am missing something crucial.

    One thing I did not understand was, why you clear the Timeout if the timeout variable gets set back to null every time you try to reconnect. So I just omitted it completely. And I also omitted the check if the wait argument is a function. I just assume it is, so it makes the code cleaner.

    var reconnectFrequencySeconds = 1;
    var evtSource;
    
    // Putting these functions in extra variables is just for the sake of readability
    var waitFunc = function() { return reconnectFrequencySeconds * 1000 };
    var tryToSetupFunc = function() {
        setupEventSource();
        reconnectFrequencySeconds *= 2;
        if (reconnectFrequencySeconds >= 64) {
            reconnectFrequencySeconds = 64;
        }
    };
    
    var reconnectFunc = function() { setTimeout(tryToSetupFunc, waitFunc()) };
    
    function setupEventSource() {
        evtSource = new EventSource("url"); 
        evtSource.onmessage = function(e) {
          console.log(e);
        };
        evtSource.onopen = function(e) {
          reconnectFrequencySeconds = 1;
        };
        evtSource.onerror = function(e) {
          evtSource.close();
          reconnectFunc();
        };
    }
    
    setupEventSource();
    

提交回复
热议问题