Server-sent events

Server-sent events is a new technology that allows the web server to send data to the browser. It works by adding an event source in JavaScript that calls a special page on the server. This page never returns but sends the events as text to the browser. If the page does return the browser will re-establish contact within a couple of seconds.

public EmptyResult Events()
{
    Response.ContentType = "text/event-stream";
    while (true)
    {
        string time = DateTime.Now.ToString();
        Response.Write("data: " + time + "\n");
        Response.Write("\n");
        Response.Flush();
        Thread.Sleep(5000);
    }
}

I used MVC for this test. After you set the content type correctly you can send event data by the syntax shown above. You can use several data: lines if you need to send multiline data. Each event is followed by an empty line. If you need to send different types of events you can name them by using an event: line. Unnamed events has the generic name message.

var events = new EventSource("events");
events.addEventListener("message", function (event) {
    alert(event.data);
}, false);

In the client we add an event source to the page URL (in my case event) and then add an event listener to it. Here we can add different listeners to different named events as described above.

Compared to WebSockets this technology doesn’t allow two-way communication. But in return it is much easier to implement. Browser support for server-sent events exist in the latest browsers except Internet Explorer 9. Unfortunately, there is no workaround for older browsers as far as I know.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s