前面讲过一篇《实现一个简单的服务端推方案》,这里讲实现的实例。
这篇讲Polling,即浏览器客户端长轮循,后端PHP短轮循数据库,功能是从数据库表读取最新的记录并显示。
客户端代码,JS库为prototype.js:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script language="JavaScript" type="text/javascript" src="./prototype.js"></script>
</head>
<body>
<script language="JavaScript">
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
}
}
}
var Comet = Class.create();
Comet.prototype = {
maxvid: 0,
url: './backend.php',
noerror: true,
initialize: function(){
},
connect: function(){
this.ajax = new Ajax.Request(this.url, {
method: 'get',
parameters: {
'maxvid': this.maxvid
},
onSuccess: function(transport){
var response = transport.responseText.evalJSON();
this.comet.maxvid = response['vid'];
this.comet.handleResponse(response);
this.comet.noerror = true;
},
onComplete: function(transport){
if (!this.comet.noerror) setTimeout(function(){
comet.connect()
}, 5000);
else
this.comet.connect();
this.comet.noerror = false;
}
});
this.ajax.comet = this;
},
handleResponse: function(response){
$('content').innerHTML += '<div>' + response['msg'] + '</div>';
}
}
var comet = new Comet();
comet.connect();
</script>
<div id="content"></div>
</body>
</html>
服务器PHP代码:backend.php
<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
flush();
//控制浏览器前端不要缓存结果,每次都要重新查询
$maxvid = $_GET["maxvid"];
error_log(date("[Y-m-d H:i:s]")." > "."maxvid: ".$maxvid."\n", 3 , "/usr/local/apache2219/logs/php_log");
$dblnk = mysql_pconnect('192.168.2.162:3306', 'root', 'cpyf');
mysql_select_db('app_m1p', $dblnk);
if ( $maxvid <= 0 ) {
$result = mysql_query("select max(vid) from vdooropen");
$result = mysql_fetch_row($result);
$maxvid = $result[0];
}
while (1)
{
$result = mysql_query("select * from vdooropen where vid > $maxvid order by vid desc limit 1");
$num = mysql_num_rows($result);
//echo $num;
if ( $num > 0 ) break;
usleep(10000); // sleep 10ms to unload the CPU
}
$result = mysql_fetch_row($result);
// 返回 JSON 数组
$response = array();
$response['vid'] = $result[0];
$response['msg'] = $result[0].",".$result[1].",".$result[2].",".$result[3].",".$result[4];
$responseText = json_encode($response);
error_log(date("[Y-m-d H:i:s]")." < ".$responseText."\n", 3 , "/usr/local/apache2219/logs/php_log");
echo $responseText;
flush();
?>