Using HTML5 Server-Sent Events with JSON and ASP.NET MVC
The Web Dev Zone is brought to you in partnership with Mendix. Discover how IT departments looking for ways to keep up with demand for business apps has caused a new breed of developers to surface - the Rapid Application Developer.
I’m getting ready for a session that I’m delivering at the end of this month. I wanted to create a sample for using HTML5 Server-Sent Events and decided to share that sample with my Blog’s readers. But before I write about the sample, lets get to know the Server-Sent Events HTML5 API.
Pay attention that the format has to include the data: prefix and end with line break to end the message.
Another way to send data is using a dedicated event by using the event type format. The following example shows two different events that the client-side can listen for:
In order to listen to an event in the client-side all you have to do is to create an EventSource object and give it a URL to listen. Also, you need to wire the message event handler in order to handle the data arriving from the server. Here is a simple example of creating an EventSource object:
The default event source is the message event as shown in the previous example. If you want to listen for a specific event type you will need to wire a handler for that event type like in the following example which listen on the event1 event:
Server-Sent Events Using JSON and ASP.NET MVC
After we learned what are Server-Sent Events lets dive into a much more robust example. In the example, I use ASP.NET MVC as my server side technology.
We start in the client-side implementation. In the Index view of the Home controller I’ll add an messages unordered list and the script that creates the EventSource object.
As you can see I use the DOMContentLoaded event to start the script when all the DOM content finished to load. I’m creating an EventSource with the name source to listen to the home/message endpoint. Since I expect that the data returned from the server is in JSON format, I parse it using the JSON.parse function and use its content to create a new list item.
Here is the HomeController code:
Pay attention that in the Message action I’m returning the text/event-stream content type.
The following figure shows the output of running the above code:
Server-Sent Events is a good mechanism to push data from the server to the client without the need server polling. The API handles only one side communication (server to client). If you want to use a bidirectional communication channel you should look at the HTML5 Web Sockets API. Using Server-Sent Events is appropriate for listening for changes in feeds such as stocks feed or RSS feed as long as they implement the push protocol.