Thursday, 1 December 2016

Server Sent Events In MVC

Introduction

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

In order to accomplish above functionality, client sends interval basis AJAX request to server to check if data available. ServerSentEvents(SSE) api which helps server will push data to client when data is available in server.

What is 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 updates from a server when any changes occurs in server. It is mostly supported by latest browsers except Internet Explorer(IE).

Using code

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

In order to achieve the same, we need to add following action in HomeController. It sets response content type as text/event-stream. Next it loops over date and flushes data to 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 server side implementation, it's time to add code in client side to receive data from server and displays it.

First it adds a href link which calls initialize() method to implement SSE. Second it declares a div where data will display. Thirdly, it implements Server Sent Events(SSE) through javascript with below steps.
  • In first step it checks whether SSE is available in browser. If it is null then alert to end user to use other browser.
  • In second setp, if SSE is available then it create EventSource object with passing URL as parameter. Next it inject following events.

    • onopen it calls when connection is opened to server
    • onmessage it calls when browser gets any message from server
    • onclose it calls when 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> 
 
 
 
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 server to client when any changes occurs in server side. If you want to use a bidirectional communication channel you can use the HTML5 Web Sockets API. Disadvantage of SSE is it browser dependent. If browser doesn't support SSE then user can't see data, but it is easy to use it. You can also use SignalR for realtime pushing data to end user.

Hope this helps.

No comments:

Post a Comment