Comet is 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 classic AJAX. In classic AJAX applications, 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 periodic AJAX request must happen in order to get new data fro the server.

 

I will now explain how to implement Comet with PHP programming language. I will demonstrate it on two demos which uses two techniques: the first one is based on hidden "<iframe>" and the second one is based on classic AJAX non-returning request. The first demo will simply show the server date in real time on the clients and the second demo will display a mini-chat.
Comet with iframe technique : server timestamp demo

We need:
A PHP script that will handle the persistent http request (backend.php)
A HTML file that will load Javascript code and that will show the data coming from the server (index.html)
The prototype library that will help us to write simple JS code

To understand how it works this schema should help:
 
The backend script (PHP)

This script will do an infinite loop and will return the server time as long as the client is connected. Call it "backend.php":

1 <?php
2
3 header("Cache-Control: no-cache, must-revalidate");
4 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
5 flush();
6
7 ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
8 <html xmlns="http://www.w3.org/1999/xhtml">
9 <head>
10
11 <title>Comet php backend</title>
12 <meta http-equiv="Content-Type" content="text/html; charsrks this schema should helpet=utf-8" />
13 </head>
14 <body>
15
16 <script type="text/javascript">
17 // KHTML browser don't share javascripts between iframes
18   var is_khtml = navigator.appName.match("Konqueror") || navigator.appVersion.match("KHTML");
19 if (is_khtml)
20 {
21 var prototypejs = document.createElement('script');
22 prototypejs.setAttribute('type','text/javascript');
23 prototypejs.setAttribute('src','prototype.js');
24 var head = document.getElementsByTagName('head');
25 head[0].appendChild(prototypejs);
26 }
27 // load the comet object
28   var comet = window.parent.comet;
29
30 </script>
31
32 <?php
33
34 while(1) {
35 echo '<script type="text/javascript">';
36 echo 'comet.printServerTime('.time().');';
37 echo '</script>';
38 flush(); // used to send the echoed data to the client
39   sleep(1); // a little break to unload the server CPU
40   }
41
42 ?>
43
44 </body>
45 </html>

 


The client script (HTML)

 

This HTML document first load the prototype library in the "<head>" tag, then it create the tag that will contains the server timer "<div id="content"></div>", and finally it create a "comet" javascript object that will connect the backend script to the time container tag.

The comet object will create some invisible "iframe" tags (depends on the web browser). These iframes are in charge to create the background persistent http connection with the backend script. Notice: this script do not handle possible connection problems between client and server.

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title>Comet demo</title>
5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6 <script type="text/javascript" src="prototype.js"></script>
7
8 </head>
9 <body>
10 <div id="content">The server time will be shown here</div>
11
12 <script type="text/javascript">
13 var comet = {
14 connection : false,
15 iframediv : false,
16
17 initialize: function() {
18 if (navigator.appVersion.indexOf("MSIE") != -1) {
19
20 // For IE browsers
21   comet.connection = new ActiveXObject("htmlfile");
22 comet.connection.open();
23 comet.connection.write("<html>");
24 comet.connection.write("<script>document.domain = '"+document.domain+"'");
25 comet.connection.write("</html>");
26 comet.connection.close();
27 comet.iframediv = comet.connection.createElement("div");
28 comet.connection.appendChild(comet.iframediv);
29 comet.connection.parentWindow.comet = comet;
30 comet.iframediv.innerHTML = "<iframe id='comet_iframe' src='./backend.php'></iframe>";
31
32 } else if (navigator.appVersion.indexOf("KHTML") != -1) {
33
34 // for KHTML browsers
35   comet.connection = document.createElement('iframe');
36 comet.connection.setAttribute('id', 'comet_iframe');
37 comet.connection.setAttribute('src', './backend.php');
38 with (comet.connection.style) {
39 position = "absolute";
40 left = top = "-100px";
41 height = width = "1px";
42 visibility = "hidden";
43 }
44 document.body.appendChild(comet.connection);
45
46 } else {
47
48 // For other browser (Firefox...)
49   comet.connection = document.createElement('iframe');
50 comet.connection.setAttribute('id', 'comet_iframe');
51 with (comet.connection.style) {
52 left = top = "-100px";
53 height = width = "1px";
54 visibility = "hidden";
55 display = 'none';
56 }
57 comet.iframediv = document.createElement('iframe');
58 comet.iframediv.setAttribute('src', './backend.php');
59 comet.connection.appendChild(comet.iframediv);
60 document.body.appendChild(comet.connection);
61
62 }
63 },
64
65 // this function will be called from backend.php
66   printServerTime: function (time) {
67 $('content').innerHTML = time;
68 },
69
70 onUnload: function() {
71 if (comet.connection) {
72 comet.connection = false; // release the iframe to prevent problems with IE when reloading the page
73   }
74 }
75 }
76 Event.observe(window, "load", comet.initialize);
77 Event.observe(window, "unload", comet.onUnload);
78
79 </script>
80
81 </body>
82 </html>

 

 

Here is the tar.gz archive of this demo.
Comet with classic AJAX : litte chat demo

As on the above technique, we need:
A file to exchange data (data.txt)
A PHP script that will handle the persistent http request (backend.php)
A HTML file that will load Javascript code and that will show the data coming from the server (index.html)
The prototype library that will help us to write simple JS code
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

1 <?php
2
3 $filename = dirname(__FILE__).'/data.txt';
4
5 // store new message in the file
6   $msg = isset($_GET['msg']) ? $_GET['msg'] : '';
7 if ($msg != '')
8 {
9 file_put_contents($filename,$msg);
10 die();
11 }
12
13 // infinite loop until the data file is not modified
14   $lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
15 $currentmodif = filemtime($filename);
16 while ($currentmodif <= $lastmodif) // check if the data file has been modified
17   {
18 usleep(10000); // sleep 10ms to unload the CPU
19   clearstatcache();
20 $currentmodif = filemtime($filename);
21 }
22
23 // return a json array
24   $response = array();
25 $response['msg'] = file_get_contents($filename);
26 $response['timestamp'] = $currentmodif;
27 echo json_encode($response);
28 flush();
29
30 ?>

 


The client script (HTML)

 

This HTML document first load the prototype library in the "<head>" tag, then it create the tag "<div id="content"></div>" 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 send AJAX requests 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.

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <title>Comet demo</title>
5
6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
7 <script type="text/javascript" src="prototype.js"></script>
8 </head>
9 <body>
10
11 <div id="content">
12 </div>
13
14 <p>
15 <form action="" method="get" onsubmit="comet.doRequest($('word').value);$('word').value='';return false;">
16 <input type="text" name="word" id="word" value="" />
17 <input type="submit" name="submit" value="Send" />
18 </form>
19 </p>
20
21 <script type="text/javascript">
22 var Comet = Class.create();
23 Comet.prototype = {
24
25 timestamp: 0,
26 url: './backend.php',
27 noerror: true,
28
29 initialize: function() { },
30
31 connect: function()
32 {
33 this.ajax = new Ajax.Request(this.url, {
34 method: 'get',
35 parameters: { 'timestamp' : this.timestamp },
36 onSuccess: function(transport) {
37 // handle the server response
38   var response = transport.responseText.evalJSON();
39 this.comet.timestamp = response['timestamp'];
40 this.comet.handleResponse(response);
41 this.comet.noerror = true;
42 },
43 onComplete: function(transport) {
44 // send a new ajax request when this request is finished
45   if (!this.comet.noerror)
46 // if a connection problem occurs, try to reconnect each 5 seconds
47   setTimeout(function(){ comet.connect() }, 5000);
48 else
49 this.comet.connect();
50 this.comet.noerror = false;
51 }
52 });
53 this.ajax.comet = this;
54 },
55
56 disconnect: function()
57 {
58 },
59
60 handleResponse: function(response)
61 {
62 $('content').innerHTML += '<div>' + response['msg'] + '</div>';
63 },
64
65 doRequest: function(request)
66 {
67 new Ajax.Request(this.url, {
68 method: 'get',
69 parameters: { 'msg' : request
70 });
71 }
72 }
73 var comet = new Comet();
74 comet.connect();
75 </script>
76
77 </body>
78 </html>

 

下载:https://files.cnblogs.com/wangbin/cometd.rar

http://www.zeitoun.net/articles/comet_and_php/start

posted on 2010-09-09 17:08  Dufe王彬  阅读(311)  评论(0编辑  收藏  举报