AJAX - The Complete Reference

(avery) #1

PART III


Chapter 10: Web Services and Beyond 527


</head>
<body>
<h1>Opera Server Events</h1>
<div id="hellodiv"></div>
</body>
</html>

On the server side, we need to pump out events for the browser to receive. We note that
we must indicate a new MIME type application/x-dom-event-stream for our client
updates. We also put the changes in the following form:

Event: event-name\n
data: data-to-send\n\n

A very simple program that outputs the time in this event stream format is shown here:

<?php
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Type: application/x-dom-event-stream");
while (true)
{
$message = "Hello World at ". date("h:i:s A");
print "Event: update_time\n";
print "data: ". $message. "\n\n";
ob_flush();
flush();
sleep(2);
}
?>

If you have a browser that supports this style of push, such as Opera 9, give it a whirl at
http://ajaxref.com/ch10/opera.html.

NNOT EOTE You may wonder how this idea works communications-wise. Inspection with many browser
level monitoring tools will interfere with the communications mechanism, but when we used a
raw network capture it appeared that the approach uses an unending HTTP request pattern
similar to the endless iframe, at least in the current instantiation in Opera 9.

The Comet Challenge: Web Chat

If you say anything at all about Comet, you have to include some mention of chat. We
implemented a basic chatting system using all the methods previously discussed. You can
find a page pointing to each of them at http://ajaxref.com/ch10/chat.html.
Architecturally, chat presents some interesting challenges. For example, when a user
types a message, if you wait to get a response back from the server before updating the page,
it really seems quite slow to the end user. However, if you directly post the message client
side, you face a clock skew problem because your local posts are slightly different than
server posted messages. If you opt for posting your own messages locally, you don’t need to
fetch those from the server; you only want other people’s messages. Even monitoring user
Free download pdf