シンプルな 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);
}
});
}
ブラウザーが Ajax 呼び出しでタイムアウトしないようにするには、60 秒のタイムアウトが必要です。
このように、QUERY の結果が変更されると (レコードが挿入され、レコードが更新されます)、PHP 呼び出しが戻り、Ajax がその結果を取得します。