Alex Rivera | Logout

How do server-sent events actually work?

Asked 2011-10-03T14:09:46.407
82

So I understand the concept of server-sent events (EventSource):

  • A client connects to an endpoint via EventSource
  • Client just listens to messages sent from the endpoint

The thing I'm confused about is how it works on the server. I've had a look at different examples, but the one that comes to mind is Mozilla's: http://hacks.mozilla.org/2011/06/a-wall-powered-by-eventsource-and-server-sent-events/

Now this may be just a bad example, but it kinda makes sense how the server side would work, as I understand it:

  • Something changes in a datastore, such as a database
  • A server-side script polls the datastore every Nth second
  • If the polling script notices a change, a server-sent event is fired to the clients

Does that make sense? Is that really how it works from a barebones perspective?

Edit
Report

1 Answer

120

The HTML5 doctor site has a great write-up on server-sent events, but I'll try to provide a (reasonably) short summary here as well.

Server-sent events are, at its core, a long running http connection, a special mime type (text/event-stream) and a user agent that provides the EventSource API. Together, these make the foundation of a unidirectional connection between a server and a client, where messages can be sent from server to client.

On the server side, it's rather simple. All you really need to do is set the following http headers:

Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive

Be sure to respond with the code 200 and not 204 or any other code, as this will cause compliant user agents to disconnect. Also, make sure to not end the connection on the server side. You are now free to start pushing messages down that connection. In nodejs (using express), this might look something like the following:

    app.get("/my-stream", function(req, res) {
        res.status(200)
           .set({ "content-type"  : "text/event-stream"
                , "cache-control" : "no-cache"
                , "connection"    : "keep-alive"
                })

        res.write("data: Hello, world!\n\n")
    })

On the client, you just use the EventSource API, as you noted:

    var source = new EventSource("/my-stream")
    source.addEventListener("message", function(message) {
        console.log(message.data)
    })

And that's it, basically.

Now, in practice, what actually happens here is that the connection is kept alive

answered 2012-08-17T01:56:49.200

Your Answer