Sunday, May 13, 2012

HTML5 Server-sent-Events (using Asp.Net)

       This post may help Asp.Net developers to understand and use Server-sent-Events in their Web Applications. The sample code (provided as download below) demonstrates a simple communication between client(browser) and server, it follows these steps:
  • Client Initiates the process by opening a connection to server.
  • Server pings Client with current Time for every 2second interval for 5 times.
  • After 5 times, Client closes the connection with Server.
       Its useful in transmitting real-time updates as streams of data directly to connected web browsers. Check Server-sent-Events API (events, properties, methods) at MDN site, also check for versions of browsers supporting it. The sample code i provided is just an Asp.Net version of Server-sent-Events in PHP available at MDN.

Above is the screenshot for sample in action (from firefox browser).
   
      You may require to uncomment this line in code:
    //Response.Headers.Add("Content-Type", "text/event-stream\n\n");
    while working against IIS7 and higher versions of web-server.


Note: use other than IE browsers with HTML5 support.

References:
  1.     https://developer.mozilla.org/en/Server-sent_events/Using_server-sent_events
  2.     http://www.w3.org/TR/2011/WD-eventsource-20110208/
Download link:
          Download the code files from here.