HTML5 Event Sources with Scala Spray
With the onset of HTML5 modern browsers (read: everyone but IE) implemented the W3C’s Server-Sent Events feature. This essentially allows you to push events from server to client without any additional hacks like long polling, or additional protocols like Web Sockets. This is exceedingly neat as it allows you to do stream-events with a very tiny API and minimal effort on that part of the developer.
Recently i’ve been doing a fair bit with the Scala Spray toolkit when building HTTP services, so I thought i’d take it for a spin and see how trivial it would be to implement SSE. Turns out it was pretty simple. Here’s a demo:
As mentioned in the demo video, most of the SSE tutorials you’ll find online don’t talk about streaming events, they just talk about having an event source HTTP resource for which the browser will consume events. The massive omission here is that if the server just closes the connection like any regular request, then you essentially have to wait for the retry
period to pass before the browser will then automatically reconnect. This is not really that great as it just gives you a more convenient API for polling (how 90s!). On the one hand, if you have a low volume of events, or a bit of lag between updates doesn’t hurt then it may not be an issue, but in the main i’d imagine that most people wanting a stream of events would want exactly that, a stream. This is achieved by using chunking the response server side, and the content flushed to the client with the SSE’s mandatory “data:” prefix will then be operated on, giving you a handy stream of data. Of course, you’ll have to close that connection at some point, but if you set the retry latency to a low value then you’ll just move from stream to stream with very little lag (as per the example video).
In the broad sense, this kind of approach is useful in a wide set of circumstances to improve the user experience. I’ve rambled on about this before, but now with SSE there is a generic way of achieving it without needing a framework or platform that explicitly makes comet-style programming easy: its broadly accessible for all toolkits.
The code for the example application I demoed in the video can be found on github. Enjoy.