1. Back To Blog

Why do we need HTML 5 server-sent events? (ASP.NET HTML interview questions)

One of the common requirements in web world is getting updates from the server. Take example of a stock ticker application where the browser has to take regular updates from the server for the recent stock value.

                                        

                                            

 

Now to implement this kind of requirement developers normally write some kind of PULL code which goes to the server and fetches data in certain interval. Now PULL solution is good but it makes the network chatty with lot of calls and also it adds load on the server.

 

So rather than PULL it would be great if we can have some kind of PUSH solution. In simple words when the server has updates it will send updates to the browser client. That can be achieved by using "SERVER SENT EVENTS".

 

So the first thing the browser needs to do is connect to the server source which will send updates. Let's say we have page "stock.aspx" which sends stock updates. So to connect to the page we need to use attach to the event source object as shown in the below code.

 

   var source = new EventSource("stock.aspx");

 

We also need to attach the function where we will receive messages when server sends update. For than we need to attach function to the "onmessage" event as shown in the below code.

        source.onmessage = function (event)

            document.getElementById("result").innerHTML += event.data + "<br>";

        };

 

Now from the server side we need to send events. Below are some lists of important events with command that needs to be sent from the server side.

 

Event

Command

Send data to the client.

data : hello

Tell client to retry in 10 seconds

retry : 10000

Raise a specific event with data

event : success

data : You are logged in.

 

So for example if we want to send data below is the ASP.NET code for the same. Please note the content type is set to text/event.

 

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

Response.Expires=-1;

Response.Write("data: " + DateTime.Now.ToString());

Response.Flush();

 

To retry after 10 second below is the command.

 

Response.Write("retry: 10000");

 

If you want to attach an event we need to use the "addEventListener" event as shown in the below code.

 

source.addEventListener('message', function(e)

  console.log(e.data);

}, false);

 

From the server side the below message will trigger the "message" function of javascript.

 

event: message

data : hello

 

If you are preparing for ASP.NET interviews , below is a nice video created by www.questpond.com for last minute revision

 

Shiv Prasad Koirala

Visit us @ www.questpond.com or call us at 022-66752917... read more

We are on Social