Search code examples
javascripthtmlserver-sent-events

HTML5 Server sent events: technical details?


I'm interested in the technical background of HTML5's new server sent events. What really happens there?

  • you don't need a special feature on the server side - just send your data as always, e.g. html
  • HTTP is still a request/response protocol. The new Content-type "text/event-stream" does not change that in my opinion

So is this concept just an encapsulated version of "plain old long polling"? On the other hand, it is often described as a persistent, bi-directional connection to the server.. that would be something different in my opinion. I just want to unterstand how this can work on top of http.


Solution

  • It's more a codification of forever frame than long polling, relying on chunked transfer encoding rather than holding the connection open until data is ready. The data sent in the events is just text, though that text can, of course, be HTML, it's up to your app to do the appropriate stuff with it. Items in the event stream look like this:

    event: message
    data: Any text data you want goes here
    

    In the browser, when it receives this chunk, you see an event message on the EventSource which you can capture with the familiar addEventListener("message", callback) approach.

    The main benefit over forever frame (or long polling) is a standardized interface (so basically, not worth updating existing working code for), the main advantage over Web Sockets is that it'll work just fine on cheap shared hosting where long running processes are not allowed.

    P.S. The technical details are all in the spec