How to implement COMET with PHP

来源:转载

How to implement COMET with PHP

Cometis a programming technique that enables web servers to send data to the client without having any need for the client to request it. This technique will produce more responsive applications than classicAJAX. In classicAJAXapplications, web browser (client) cannot be notified in real time that the server data model has changed. The user must create a request (for example by clicking on a link) or a periodicAJAXrequest must happen in order to get new data fro the server.


I will now explain how to implement Comet withPHPprogramming language. I will demonstrate it on two demos which uses two techniques: the first one is based on hidden "";
} else if (navigator.appVersion.indexOf("KHTML") != -1) {
// for KHTML browsers
comet.connection = document.createElement('iframe');
comet.connection.setAttribute('id', 'comet_iframe');
comet.connection.setAttribute('src','./backend.php');
with (comet.connection.style) {
position = "absolute";
left= top = "-100px";
height = width = "1px";
visibility = "hidden";
}
document.body.appendChild(comet.connection);
} else {
// For other browser (Firefox...)
comet.connection = document.createElement('iframe');
comet.connection.setAttribute('id', 'comet_iframe');
with (comet.connection.style) {
left= top = "-100px";
height = width = "1px";
visibility = "hidden";
display= 'none';
}
comet.iframediv = document.createElement('iframe');
comet.iframediv.setAttribute('src', './backend.php');
comet.connection.appendChild(comet.iframediv);
document.body.appendChild(comet.connection);
}
},
// this function will be called from backend.php
printServerTime: function (time) {
$('content').innerHTML = time;
},
onUnload: function() {
if (comet.connection) {
comet.connection = false; // release the iframe to prevent problems with IE when reloading the page
}
}
}
Event.observe(window, "load", comet.initialize);
Event.observe(window, "unload", comet.onUnload);
</script>

Download it

Here is thetar.gz archiveof this demo.

Comet with classic AJAX : litte chat demo

As on the above technique, we need:

A file to exchange data (data.txt)


APHPscript that will handle the persistent http request (backend.php)


AHTMLfile that will load Javascript code and that will show the data coming from the server (index.html)


Theprototypelibrary that will help us to write simpleJScode


The backend script (PHP)

This script will do two things:

Write into "data.txt" when new messages are sent


Do an infinite loop as long as "data.txt" file is unchanged

<?php
$filename= dirname(__FILE__).'/data.txt';
// store new message in the file
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
if ($msg != '')
{
file_put_contents($filename,$msg);
die();
}
// infinite loop until the data file is not modified
$lastmodif= isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) // check if the data file has been modified
{
usleep(10000); // sleep 10ms to unload the CPU
clearstatcache();
$currentmodif = filemtime($filename);
}
// return a json array
$response = array();
$response['msg']= file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush();
?>The client script (HTML)

ThisHTMLdocument first load the prototype library in the "" tag, then it create the tag "" that will contains the chat messages comming from "data.txt" file, and finally it create a "comet" javascript object that will call the backend script in order to watch for new chat messages.


The comet object will sendAJAXrequests each time a new message has been received and each time a new message is posted. The persistent connection is only used to watch for new messages. A timestamp url parameter is used to identify the last requested message, so that the server will return only when the "data.txt" timestamp is newer that the client timestamp.





Comet demo

<script type="text/javascript" src="prototype.js"></script>










<script type="text/javascript">
var Comet = Class.create();
Comet.prototype = {
timestamp: 0,
url: './backend.php',
noerror: true,
initialize: function() { },
connect: function()
{
this.ajax = new Ajax.Request(this.url, {
method: 'get',
parameters: { 'timestamp' : this.timestamp },
onSuccess: function(transport) {
// handle the server response
var response = transport.responseText.evalJSON();
this.comet.timestamp = response['timestamp'];
this.comet.handleResponse(response);
this.comet.noerror = true;
},
onComplete: function(transport) {
// send a new ajax request when this request is finished
if (!this.comet.noerror)
// if a connection problem occurs, try to reconnect each 5 seconds
setTimeout(function(){ comet.connect() }, 5000);
else
this.comet.connect();
this.comet.noerror = false;
}
});
this.ajax.comet = this;
},
disconnect: function()
{
},
handleResponse: function(response)
{
$('content').innerHTML += '' + response['msg'] + '';
},
doRequest: function(request)
{
new Ajax.Request(this.url, {
method: 'get',
parameters: { 'msg' : request
});
}
}
var comet = new Comet();
comet.connect();
</script>

Download it

Here is thetar.gz archiveof this demo.


If you liked this article please flattr me

分享给朋友:
您可能感兴趣的文章:
随机阅读: