HTML and CSS Reference
In-Depth Information
Figure 11-6. Server-sent events in action
The web form consists of a Start Listening button. Clicking the button opens a connection with a
generic handler ( ClientNotiier.ashx ) residing on the server. The generic handler is designed in such a way
that it sends a notification in the form of the server time to the client every 15 seconds for 1 minute. You
see the outputted time at those intervals. The messages, including the notification data, are displayed in a
<div> element.
The JavaScript code behind the working of the web form is shown in Listing 11-13.
Listing 11-13. Initiating the Server-Sent Events
$(document).ready(function () {
if (window.EventSource == undefined) {
alert(“This browser doesn't support HTML5 Server Sent Events.”);
return;
}
$(“#btnListen”).click(function () {
var source = new EventSource('ClientNotifier.ashx');
source.addEventListener(“open”, function (event) {
$('#targetDiv').append('<h3>Connection Opened.</h3>');
},false);
source.addEventListener(“error”, function (event) {
if (event.eventPhase == EventSource.CLOSED) {
$('#targetDiv').append('<h3>Connection Closed.</h3>');
}
},false);
source.addEventListener(“message”,function (event) {
$('#targetDiv').append('<h3>' + event.data + '</h3>');
},false);
});
});
 
Search WWH ::




Custom Search