php代码:为了ajax请求超时和是在usleep前加上错误抑制符,或者修改php.ini 的超时时间
-
<?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();
-
- ?>
复制代码
html代码:
-
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
-
<html xmlns=”http://www.w3.org/1999/xhtml”>
-
<head>
-
<title>Comet demo</title>
-
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
-
<script type=”text/javascript” src=”jquery-1.3.2.min.js”></script>
-
<script>
-
var timestamp = 0;
-
var url = ‘backend.php’;
-
var error = false;
-
function connect(){
-
$.ajax({
-
data : {‘timestamp’ : timestamp},
-
url : url,
-
type : ‘get’,
-
timeout : 0,
-
success : function(response){
-
var data = eval(‘(‘+response+’)’);
-
error = false;
-
timestamp = data.timestamp;
-
$(“#content”).append(‘<div>’ + data.msg + ‘</div>’);
-
},
-
error : function(){
-
error = true;
-
setTimeout(function(){ connect();}, 5000);
-
},
-
complete : function(){
-
if (error)
-
// if a connection problem occurs, try to reconnect each 5 seconds
-
setTimeout(function(){connect();}, 5000);
-
else
-
connect();
-
}
-
})
-
}
-
function send(msg){
-
$.ajax({
-
data : {‘msg’ : msg},
-
type : ‘get’,
-
url : url
-
})
-
}
-
$(document).ready(function(){
-
connect();
-
})
-
</script>
-
</head>
-
<body>
-
-
<div id=”content”>
-
</div>
-
-
<p>
-
<form action=”” method=”get” onsubmit=”send($(‘#word’).val());$(‘#word’).val(”);return false;”>
-
<input type=”text” name=”word” id=”word” value=”” />
-
<input type=”submit” name=”submit” value=”Send” />
-
</form>
-
</p>
-
-
</body>
- </html>
复制代码
但是光这样是不足以投入使用的,在测试中本人发现两个问题:
1. HTTP 1.1规定客户端不应该与服务器端建立超过两个的HTTP连接,新的连接会被阻塞。而IE系列8.0以下版本的浏览器就是这么做的,所以若同时打开两个浏览器窗口(IE8.0以下)或者是刷新了页面,程序就死掉了。
2. 通常情况下web服务器允许脚本最大执行时间是30秒,所以要让程序正常运行,就需要将服务器的脚本最大执行时间设置成无限,但似乎也不是上上策。
但事实证明php是可以很好地实现服务器推技术的,如phpfreechat即时聊天室,开心网和白社会的即时消息都是成功案例(它们都不会出现上面的两个问题)。
转载请注明:cooljun小窝 » Jquery+php实现comet(http长连接)
如果你觉得这篇文章对你有帮助,请支持我继续更新网站 !捐赠本站