19 September, 2010

PHP Comet basics

Despite improving the user experience, Ajax still uses the HTTP model, i.e. client sending request for some resource to server and server responding to this request from client. This is generally called "Pull" method/architecture.
However, Comet, the stuff this article is on, uses "Push" architecture. Lets consider ana analogy: in case of chat systems, server pushes data to client as and when necessary at some intervals, as a result of which, communication between the two (client/server) is fast. If, chat systems would have been built using "Pull" method, then the communication would suffer.
Comet pushes information to the client via HTTP streaming. Simply saying, HTTP streaming is a continuous connection with the server that pushes data out to client at certain intervals.
Lets consider some sample code:

//get time the file was modified on
$changed = filemtime("some_file.txt");
$lastChanged = $changed;

//clear the file stats; so that file operation results are cleared
clearstatcache();

//check if it has changed; runs infinitely just for a test; remove this in
//real cases
while(true) {

//sleep for 3 secs; can be set as appropriate to create a delay
sleep(3);

//check the file modified time
$lastChanged = filemtime("some_file.txt");

//clear the file stats; so that file operation results are cleared
clearstatcache();

//check the times
if($changed != $lastChanged) {
$outData = date("d:i:s", $lastChanged);
?>

//send the data across HTTP stream
ob_flush();
flush();
$changed = $lastChanged;
sleep(3);
}
}
?>

Since Comet focuses more on traditional web application servers, it is preferrable to use a system specially designed for HTTP streaming.

No comments: