Server-Sent Events in HTML5
The world wide web and the Internet started as a stateless
content delivery mechanism, taking a step backwards compared to traditional
desktop applications. Early Internet applications needed to explicitly request
every piece of information, and the server sent only the requested data.
Then came what we now call “Web 2.0 application
development”: Dynamic HTML, heavy usage of JavaScript, AJAX, and various
plugins (Adobe Flash and Microsoft Silverlight). These applications were
dynamic and responsive, and they brought much of that rich interactive
experience users enjoyed in desktop client/server applications to the Internet.
However, due to the request and response architecture that these applications
are based on, the latest Rich Internet Applications still cannot match the
connectivity and the capability to get real-time data that client/server
applications had more than a decade ago.
The
reason is that these applications still need to initiate the communication from
the web browser to get some data from the server: that is, the client part of
the application running in the web browser has no way to know whether the
server has some data for it.
This requirement is solved by making the client constantly
ask the server whether there’s some data ready for it. This is what is called polling.
By using this technique, the web application essentially polls the server on a
regular basis, based on a timer, using a simple HTTP request each time the
timer expires. However, the cost of polling frequently is very high – both in
terms of network bandwidth as well as server infrastructure needed to support a
huge number of polling requests. The server must have the capability to buffer
the data that it needs to send to the client until the next request comes from
the client.
The evolution: server-sent events & Web Sockets
HTML 5 solve this problem. The Communication section in the
HTML 5 specification section introduces server-sent events and Web Sockets.
These new features enable a new paradigm of web application programming that
will revolutionize the way to develop and deploy web applications.
WebSockets is a more advanced solution which allow you to
communicate back and forth with the server using a regular socket. This could
be very useful in applications where a lot of data is sent both to and from the
client and response time is of the essence.
Server Side Events is a more basic way to send one way data
from the server to the client. It works like a long request from the clients
JavaScript function where data can is returned bit by bit during the response
and each time a bit is returned a JavaScript event is triggered.
In this post, we will see more about Server Sent Events. The
server-sent event HTML 5 specification introduces a new DOM element called eventsource.
A server-sent event is when a web page automatically gets
updates from a server.
This was also possible before, but the web
page would have to ask if any updates were available. With server-sent events,
the updates come automatically.
Examples: Facebook/Twitter updates, stock
price updates, news feeds, sport results, etc.
The three things you should know about Server-Sent Events are:
·
uni-directional (only server push, initiated
by client)
·
using pure HTTP
·
not using polling
NOTE: Server Side Events is currently only supported in a
few browsers such as latest Chrome, Safari, Opera 9+ and Firefox 6.0 Beta so
make sure you use one of these browsers.
Explanation with Example:
Start off by creating a Web Application Project in Visual
Studio and add the following HTML to Default.aspx:
<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
<title>Server-Sent
Events</title>
<script>
function initialize() {
}
</script>
</head>
<body onload="initialize()">
<form id="form1" runat="server">
<div id="divMessageNotification">
</div>
</form>
</body>
</html>
Add DisplayTime.aspx file in the project and add the
following code in the Page_Load function of code behind file
DisplayTime.aspx.cs:
protected void Page_Load(object
sender, EventArgs e)
{
DateTime startDate = DateTime.Now;
Response.ContentType = "text/event-stream";
Response.Expires = -1;
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();
}
We tell the browser that
this is a Server Side Events response by setting the content type of our page
to text/event-stream.
Response.ContentType = "text/event-stream";
Make sure that EventSource is supported by the browser:
if
(window.EventSource == undefined) {
document.getElementById('targetDiv').innerHTML =
"Your browser doesn't support Server Side Events.";
return;
}
The following line will create an EventSource which will
load the DisplayTime.aspx page; we will now hook up our events to it.
var source = new EventSource('DisplayTime.aspx');
Now we will create three events handlers:
onopen
event handler, this is triggered when the initial request to the server is
made. We’ll print out “Time
Started” to our div when this happens
source.onopen = function (event) {
document.getElementById(‘divMessageNotification’).innerHTML += 'Time Started.<br>';
};
onerror event handler which will be triggered if the
connection is closed or an error occurs. We’ll print out “Time Finished” if
the connection was closed.
source.onerror = function (event) {
if
(event.eventPhase == EventSource.CLOSED) {
document.getElementById(‘divMessageNotification’).innerHTML += 'Time Finished.<br>';
}
};
onmessage event handler which will be triggered every
time new data arrived from our request, the data can be reached using
event.data and we’ll just print it out to our divMessageNotification.
source.onmessage = function (event) {
document.getElementById(‘divMessageNotification’).innerHTML += event.data + '<br>';
};
This is a basic example
of how to use Server-Sent Events with ASP.NET, there’s a lot of possibilities
with Server-Sent Events such as JSON support for serialized classes if more
advanced data is required.
Remember the following:
·
Set the "Content-Type" header to
"text/event-stream"
·
Specify that the page should not cache
·
Output the data to send (Always start
with "data: ")
·
Flush the output data back to the web page
EventSource object’s
events which we have seen in our example.
onopen
|
When
a connection to the server is opened
|
onmessage
|
When
a message is received
|
onerror
|
When
an error occurs
|
Comments
Post a Comment