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

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

    As someone already mentioned different browsers do different things depending on the return code. What I do instead is just close the connection regardless then check server health to make sure its up again. I think its silly trying to re-open a stream if we don't actually know if the server/proxy is back yet.

    Tested in FF and Chrome:

    let sseClient
    
    function sseInit() {
      console.log('SSE init')
      sseClient = new EventSource('/server/events')
      sseClient.onopen = function () { console.log('SSE open ') }
      sseClient.onmessage = onMessageHandler
      sseClient.onerror = function(event) {
        if (event.target.readyState === EventSource.CLOSED) {
          console.log('SSE closed ' + '(' + event.target.readyState + ')')
        } else if (event.target.readyState === EventSource.CONNECTING) {
          console.log('SSE reconnecting ' + '(' + event.target.readyState + ')')
          sseClient.close()
        }
      }
    }
    
    sseInit()
    
    setInterval(function() {
      let sseOK
      if (sseClient === null) {
        sseOK = false
      } else {
        sseOK = (sseClient.readyState === EventSource.OPEN)
      }
      if (!sseOK) {
        // only try reconnect if server health is OK
        axios.get('/server/health')
          .then(r => {
            sseInit()
            store.commit('setServerOK_true')
          })
          .catch(e => {
            store.commit('setServerOK_false')
            sseClient = null
          })
      }
    }, 5000)
    

    Note, I am using Vue with ECMAScript and tracking state in a store so some things might not make immediate sense.

提交回复
热议问题