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.
On Chrome 35 or Opera 22, if you lose your connection to the server, it will try to reconnect indefinitely every few seconds until it succeeds. On Firefox 30, on the other hand, it will only try once and then you have to either refresh the page or handle the error event raised and manually reconnect.
I much prefer the way Chrome or Opera does it, but reading http://www.w3.org/TR/2012/WD-eventsource-20120426/#processing-model, it seems as though once the EventSource tries to reconnect and fails due to a network error or other, it shouldn't retry the connection. Not sure if I'm understanding the spec correctly, though.
I was set on requiring Firefox to users, mostly based on the fact that you can't have multiple tabs with an event stream from the same URL open on Chrome, but this new finding would probably be more of an issue. Although, if Firefox behaves according to spec then I might as well work around it somehow.
Edit:
I'm going to keep targeting Firefox for now. This is how I'm handling reconnections:
var es = null;
function initES() {
if (es == null || es.readyState == 2) { // this is probably not necessary.
es = new EventSource('/push');
es.onerror = function(e) {
if (es.readyState == 2) {
setTimeout(initES, 5000);
}
};
//all event listeners should go here.
}
}
initES();
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.
Server Side Events work differently in all of the browsers, but they all close the connection during certain circumstances. Chrome, for example, closes the connection on 502 errors while a server is restarted. So, it is best to use a keep-alive as others suggest or reconnect on every error. Keep-alive only reconnect at a specified interval that must be kept long enough to avoid overwhelming the server. Reconnecting on every error has the lowest possible delay. However, it is only possible if you take an approach that keeps server load to a minimum. Below, I demonstrate an approach that reconnects at a reasonable rate.
This code uses a debounce function along with reconnect interval doubling. It works well, connecting at 1 second, 4, 8, 16...up to a maximum of 64 seconds at which it keeps retrying at the same rate. I hope this helps some people.
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();
What I've noticed (in Chrome at least) is that when you close your SSE connection using close()
function, it won't try to reconnect again.
var sse = new EventSource("...");
sse.onerror = function() {
sse.close();
};
来源:https://stackoverflow.com/questions/24564030/is-an-eventsource-sse-supposed-to-try-to-reconnect-indefinitely