Last Updated: February 25, 2016
·
830
· flurin

Using EventSource for live server events

Live updates have always been kind of a hassle — you had to deal with long polling, flash components or, if you went the HTML5 route, you'd have chosen WebSockets. That's no longer the case, you can set up EventSource in about 5 lines of code and it works over standard HTTP. One small caveat though: the client can only receive data, not send it.

Check out this example where we create a live graph of server load

Holy smokes Batman, how does it work?

We created a new EventSource object with a simple var source = new EventSource(URL). This opens a long-standing connection to the specified URL (if you want to be precise about it, it closes and re-opens the connection every 60 seconds). As we want to do something with the data that's coming in, we've added an event listener to retrieve our messages. This is done with source.addEventListener("message", function(data){ ... }).

That's it basically. It's very easy as you just send text over the line and your browser handles all the resuming and error recovery for you.

Serverside we send messages over the opened connection in plain text. Each message is separated with two newline characters and consists of one or more lines of text with every line haveing a field name. The data we use for the example above looks like this:

data: [1.2, 1.3, 0.8]

The docs at the Mozilla Developer Network explain the data format pretty well.

Great, but can I use it today?

The support for this is pretty widespread nowadays. The only browser not supporting this is IE10 (who'd have guessed?). But given that it's all plain HTTP, there are several Javascript polyfills out there to bridge the gap.