demo.html
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<title>Comet Test</title>
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
(function($){
function handleResponse(response){
$('#content').append('<div>' + response['msg'] + '</div>');
}
var timestamp = 0;
var url = './chat_backend.php';
var noerror = true;
var ajax;
function connect() {
ajax = $.ajax(url, {
type: 'get',
data: { 'timestamp' : timestamp },
success: function(transport) {
eval('var response = '+transport);
timestamp = response['timestamp'];
handleResponse(response);
noerror = true;
},
complete: function(transport) {
(!noerror) && setTimeout(function(){ connect() }, 5000) || connect();
noerror = false;
}
});
}
function doRequest(request) {
$.ajax(url, {
type: 'get',
data: { 'msg' : request }
});
}
$('#cometForm').live('submit', function(){
doRequest($('#word').val());
$('#word').val('');
return false;
});
$(document).ready(function(){
connect();
});
})(jQuery);
</script>
<div id="content"></div>
<div style="margin: 5px 0;">
<form action="javascript:void(0);" id="cometForm" method="get">
<input id="word" name="word" type="text" value="">
<input name="submit" type="submit" value="Send">
</form></div>
chat_backend.php
<?php
$filename = dirname(__FILE__).'/data.txt';
// 消息都儲存在這個文件中
$msg = isset($_GET['msg']) ? $_GET['msg'] : '';
if ($msg != ''){
file_put_contents($filename,$msg);
die();
}
// 不停的循環,直到儲存消息的文件被修改
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif){ // 如果數據文件已經被修改
usleep(100000); // 100ms暫停 緩解CPU壓力
clearstatcache(); //清除緩存信息
$currentmodif = filemtime($filename);
}
// 返回json數組
$response = array();
$response['msg'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
flush();
?>