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

前端 未结 6 2004
余生分开走
余生分开走 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:45

    I read the standard the same way as you but, even if not, there are browser bugs to consider, network errors, servers that die but keep the socket open, etc. Therefore, I usually add a keep-alive on top of the re-connect that SSE provides.

    On the client-side I do it with a couple of globals and a helper function:

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

    Then I call gotActivity() at the top of connect(), and then every time I get a message. (connect() basically just does the call to new EventSource())

    On the server-side, it can either spit out a timestamp (or something) every 15 seconds, on top of normal data flow, or use a timer itself and spit out a timestamp (or something) if the normal data flow goes quiet for 15 seconds.

提交回复
热议问题