Server Sent Events In ASP.NET MVC

Introduction

In some Web Applications, we need to show real time data to the end users, which means if any changes occur (new data available) in the Server, it needs to show an end user. For instance, you are doing chat in Facebook in one tab of your Browser. You opened another tab in the same Browser and send a message to the same user (with whom, you are doing chat in the previous chat). You will see that message will appear in both the tabs and it is called real-time push.

In order to accomplish the functionality, mentioned above, the client sends interval basis AJAX requests to the Server to check, if the data is available or not. ServerSentEvents(SSE) API helps ensure the Server will push the data to the client when the data is available in the Server.

What are Server Sent Events?


SSE is an acronym and stands for Server Sent Events. It is available in HTML5 EventSource JavaScript API. It allows a Web page to get the updates from a Server when any changes occurs in the Server. It is mostly supported by the latest Browsers except Internet Explorer(IE).

Using code

We are going to implement a requirement like there is a link button and click on it and it displays current time each second on an interval basis.

In order to achieve the same, we need to add the following action in HomeController. It sets response content type as text/event-stream. Next, it loops over the date and flushes the data to the Browser.
  1. public void Message()  
  2. {  
  3.     Response.ContentType = "text/event-stream";  
  4.   
  5.     DateTime startDate = DateTime.Now;  
  6.     while (startDate.AddMinutes(1) > DateTime.Now)  
  7.     {  
  8.         Response.Write(string.Format("data: {0}\n\n", DateTime.Now.ToString()));  
  9.         Response.Flush();  
  10.   
  11.         System.Threading.Thread.Sleep(1000);  
  12.     }  
  13.       
  14.     Response.Close();  

Once we are done with the Server side implementation, it's time to add the code in the client side to receive the data from the Server and displays it.

First, it adds a href link, which calls initialize() method to implement SSE. Second, it declares a div, where the data will display. Thirdly, it implements Server Sent Events(SSE) through JavaScript with the steps, mentioned below.
  • In the first step, it checks whether SSE is available in the Browser or not. If it is null, then it alerts to the end user to use other Browser.
  • In the second step, if SSE is available, then it creates EventSource object with passing the URL as a parameter. Subsequently, it injects the events, mentioned below.

    • onopen- It calls when the connection is opened to the Server
    • onmessage- It calls when the Browser gets any message from the Server
    • onclose- It calls when the Server closes the connection.
  1. <a href="javascript:initialize();" >Click Me To See Magic</a>  
  2. <div id="targetDiv"></div>  
  3.   
  4. <script>  
  5.       
  6.     function initialize() {  
  7.         alert("called");  
  8.   
  9.         if (window.EventSource == undefined) {  
  10.             // If not supported  
  11.             document.getElementById('targetDiv').innerHTML = "Your browser doesn't support Server Sent Events.";  
  12.             return;  
  13.         } else {  
  14.             var source = new EventSource('../Home/Message');  
  15.   
  16.             source.onopen = function (event) {  
  17.                 document.getElementById('targetDiv').innerHTML += 'Connection Opened.<br>';  
  18.             };  
  19.   
  20.             source.onerror = function (event) {  
  21.                 if (event.eventPhase == EventSource.CLOSED) {  
  22.                     document.getElementById('targetDiv').innerHTML += 'Connection Closed.<br>';  
  23.                 }  
  24.             };  
  25.   
  26.             source.onmessage = function (event) {  
  27.                 document.getElementById('targetDiv').innerHTML += event.data + '<br>';  
  28.             };  
  29.         }  
  30.     }  
  31. </script> 
Output 
 
 
Figure1: Displays current time

Conclusion

Here, we discussed about SSE(Server Sent Events). It is very important API available in HTML5. It helps to push data from the Server to the client when any changes occurs in the Server side. If you want to use a bidirectional communication channel, you can use HTML5 Web Sockets API. The disadvantage of SSE is it is Browser dependent. If the Browser doesn't support SSE, then the user can't see the data, but it is easy to use it. You can also use SignalR for realtime pushing the data to the end user. 

Hope, this helps.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now