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.
public void Message()
{
Response.ContentType = "text/event-stream";
DateTime startDate = DateTime.Now;
while (startDate.AddMinutes(1) > DateTime.Now)
{
Response.Write(string.Format("data: {0}\n\n", DateTime.Now.ToString()));
Response.Flush();
System.Threading.Thread.Sleep(1000);
}
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.
<a href="javascript:initialize();" >Click Me To See Magic</a>
<div id="targetDiv"></div>
<script>
function initialize() {
alert("called");
if (window.EventSource == undefined) {
// If not supported
document.getElementById('targetDiv').innerHTML = "Your browser doesn't support Server Sent Events.";
return;
} else {
var source = new EventSource('../Home/Message');
source.onopen = function (event) {
document.getElementById('targetDiv').innerHTML += 'Connection Opened.<br>';
};
source.onerror = function (event) {
if (event.eventPhase == EventSource.CLOSED) {
document.getElementById('targetDiv').innerHTML += 'Connection Closed.<br>';
}
};
source.onmessage = function (event) {
document.getElementById('targetDiv').innerHTML += event.data + '<br>';
};
}
}
</script>
Output
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.
HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.