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
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.