我写了简单的PHP长轮询技术,阿贾克斯EN 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会得到结果。
您可以使用长轮询。它基本上是一个简单的轮询器,直到有数据才会返回。让长轮询器(通常是PHP)中的代码轮询数据库以查找事件。这种情况下,您可以在数据库上进行毫秒精确轮询,而无需使用现成的技术创建大量数据流量。 –
目前我正在使用类似的方法,但仍有差不多1.5秒。我想减少。 –
找出1.5秒来自哪里。我们创建了长达1分钟的超时轮询器,并在100毫秒内响应100毫秒轮询。 (另外:你真的需要亚秒精度吗?也许你使用的是错误的工具,然后......) –