我用简单的 PHP、Ajax 和 MySQL 编写了一个长轮询技术:
PHP代码如下:
timeout = 600;
while (timeout > 0) {
$res = db_query("QUERY");
$return_value = create_value_from_result($res);
// see if the result changed
$db_hash = md5($return_value);
if ($_SESSION['hash'] == $db_hash) {
// the result didn't change -- sleep and poll again
// usleep take microseconds, 100000 is 100 millisecond
// this is the default database polling interval
usleep(100000);
$timeout--;
} else {
// the result changed -- reply the result and set the session hash
$timeout = 0;
$_SESSION['hash'] = $db_hash;
}
}
return json_encode($return_value);
并且 Javascript 是简单的 Ajax(dojo 就是这种情况):
function longpoll() {
dojo.xhrPost({
url: 'longpolling.php',
load: function (data, ioArgs) {
data = dojo.fromJson(data);
do_magic(data);
// use settimeout to avoid stack overflows
// we could also use a while(1) loop,
// but it might give browser errors such as 'script is
// running too long' (not confirmed)
setTimeout(longpoll, 0);
}
});
}
您需要 60 秒超时以确保浏览器在 Ajax 调用上不会超时。
这样,只要 QUERY 的结果发生变化(插入记录,对记录进行更新),PHP 调用就会返回并且 Ajax 会得到它的结果。