Displaying Real Time Data using HTML5 and ASP.NET

Introduction

Some web applications need to show data in real-time. As soon as the data is generated or received at the server, it immediately needs to be displayed to the end user. Traditionally developers used to poll the server periodically to check if new data was available. This approach had its own drawbacks and proved to be unsuitable in certain cases. Wouldn’t it be nice if the server notified the client of new data rather than client checking with the server periodically? That is what HTML5 Server Sent Events (SSE) allows you to do. In this article you will learn what HTML5 Server Sent Events are and how to develop a web form that relies on real-time data from the server.

HTML5 Server Sent Events

Web applications that need to display real-time data often use “polling” techniques to fetch the latest data from the server. For example, you may develop an ASP.NET web form that makes Ajax requests to the server periodically to check whether new data is available. Accordingly the web form renders itself showing the latest data. However, such techniques have their own drawbacks including:

  • Polling techniques make too many requests to the web server if the frequency of polling is too short. This causes a burden on the server.
  • Since polling operations are performed by the client there is no way to tell the client whether new data is really available on the server. A client may keep polling the server periodically even if there is no data available. This is unnecessary overhead on the overall system.
  • Polling technique is less accurate. Since polling frequency is decided by the client and is independent of server side data availability it may so happen that data is available on the server now but the client isn’t able to show the new data until after some time gap.

Luckily, HTML5 offers a technique that can be used to display real-time data in an efficient manner – Server Sent Events (SSE). As the name suggests Server Sent Events are dispatched by the server. Using SSE you can notify the client application whenever something interesting (say availability of new data) happens on the server. The client can then take the appropriate action (say displaying the new data to the user).

Sample Application

Now that you have some idea about Server Sent Events, let’s develop a simple ASP.NET website that demonstrates how they work. In the remainder of this article you will develop a web form as shown below:

Web Form
Web Form

The above web form displays the last 5 numeric values as sent by the server to the client. The server sends a new random integer to the client after every five seconds and the client side ticker reflects the new value. Though the server sends these notifications infinitely, in this example server sends them for ten minutes. After that the connection with the server is closed. You can easily extend the concept demonstrated in this example to plot a line or bar graph of the last n values sent by the server.

Creating ASP.NET Generic Handler to Push Data

Begin by creating a new empty ASP.NET website project using Visual Studio. Then add a Generic Handler (*.ashx) and name it as SSEHandler.ashx. This generic handler will dispatch notifications to the client. Add the following code in the generic handler:

public class SSEHandler : IHttpHandler {

    public void ProcessRequest (HttpContext context) {

        HttpResponse Response = context.Response;

        DateTime startDate = DateTime.Now;

        Response.ContentType = "text/event-stream";

 while (startDate.AddMinutes(10) > DateTime.Now) { Response.Write(string.Format("data: {0}\n\n", new Random().Next(1,100))); Response.Flush(); System.Threading.Thread.Sleep(5000); }         Response.Close();

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

}

The ProcessRequest() method is where the main processing of the application takes place. The while loop essentially runs for 10 minutes. In each iteration, some data is sent to the client. Notice a couple of things about this code. Firstly, the ContentType of the Response is set to text/event-stream. This way the HTML5 capable client browser knows that this data is SSE data. The actual data is sent in a particular format:

data: <some_data>\n\n 

The data: has to be present and is followed by the actual data to be sent (a number in this example). A random number between 1 and 100 is generated using the Random class of .NET framework. The \n\n indicates the end of data fragment. Calling Flush() on the Response object ensures that all the data from the response buffer is sent to the client. The Sleep() method halts the while loop for 5 seconds just to signify some server side processing.

This is all you need in the server side code to push data to the client. Let’s move on to the client part of the application.

Receiving Data in the Client Web Form

Add a new web form in the website and key in the following markup in it:

<form id="form1" runat="server">

    <input type="button" id="btnListen" value="Start Listening" />

    <br /><br />

    <div id="headerDiv" class="tickerheading"></div>

    <div id="targetDiv" class="ticker"></div>

    <div id="footerDiv" class="tickerfooter"></div>

</form>

There is a button “Start Listening” that triggers the actual SSE mechanism. Clicking this button invokes the generic handler you developed in the previous section. The three <div> elements viz. headerDiv, targetDiv and footerDiv are used to display header, real-time data and footer respectively. The header is shown as soon as a successful connection is opened with the server. The targetDiv displays the last five values received from the server. The footerDiv is used to display a message when the server stops sending the notifications (after 10 minutes in this case).

Next, you will write some jQuery code that opens a connection with the generic handler and receives the notifications sent by the server. Make sure to refer to jQuery library in the head section of your web form.

var data = [];

 

$(document).ready(function () {

    $("#btnListen").click(function () {

        var source = new EventSource('SSEHandler.ashx');

        source.addEventListener("open", function (event) {

            $('#headerDiv').append('Latest 5 values');

        }, false);

 

        source.addEventListener("error", function (event) {

            if (event.eventPhase == EventSource.CLOSED) {

                $('#footerDiv').append('Connection Closed!');

            }

        }, false);

 

        source.addEventListener("message", function (event) {

            if (data.length >= 5)

                data = data.slice(1);

            data.push(event.data);

            var strData = '';

            for (var i = 0; i < data.length; i++) {

                strData += data[i] + '<br/>';

            }

            $('#targetDiv').hide();

            $('#targetDiv').empty();

            $('#targetDiv').html(strData);

            $('#targetDiv').slideDown(1000);

        }, false);

    });

});

The above code shows the click event handler of the btnListen. As soon as you click the “Start Listening” button the code creates a new HTML5 EventSource object. As the name suggests the EventSource is a reference to a server side source that dispatches the events (the generic handler in this case). The code further wires three event handlers of the EventSource object, viz. open, error and message.

The open event is raised when a connection is established with the event source successfully. The error event is raised when there is any error while communicating with the event source. Finally, the message event is raised whenever some data is received from the server. As you might have guessed the message event usually fires multiple times during the course of the application execution.

The open event handler simply displays a message in the header <div> element. The error event handler receives an event object that can be used to check the eventPhase of the event source. If eventPhase is CLOSED it indicates that the EventSource is no longer sending any events to the client. A message is then displayed in the footer <div> element.

The data sent by the server is stored in a global array data. The message event handler checks the length of this data array. Since you wish to display only the last five values from the server you slice the array to discard the additional values. The data sent by the server (a number in this case) is then pushed to the data array using the push() method. Notice that the data sent by the server is available on the client side as the data property of the event object (event.data). A for loop then iterates through the data array and an HTML fragment is constructed. Finally, the HTML fragment is assigned to the targetDiv element. The jQuery slideDown() essentially animates the targetDiv while the data is being displayed.

That’s it! You can run the web form and test how the server sends event notifications for ten minutes.

Summary

HTML5 Server Sent Events allow you to send notifications from the server to the client whenever something interesting happens on the server. In this article you sent numeric data to the client but you can send other types of data also such as JSON objects. HTML5 SSEs are advantageous over traditional polling techniques because the server notifies the client only when there is something interesting happening on the server. Thus HTML5 Server Sent Events are good for displaying real-time data on web pages.

About the Author:

Bipin Joshi is a blogger and author who writes about apparently unrelated topics – Yoga & technology! A former Software Consultant and Trainer by profession, Bipin is programming since 1995 and is working with .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. Having embraced Yoga way of life he now writes about Yoga, life and technology on his website. He can also be reached there.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read