首先,我要感谢所有对新程序员非常有帮助的伟大人物。
我有一个关于长轮询的问题。我已经阅读了一些关于Comet编程的长轮询技术的文章。这种方法对我来说似乎很困难,因为有时还需要在服务器端安装一些脚本。
现在,我找到了一个关于长轮询的示例。它运行得很好,但我不确定它是否是正确的方法。这个示例脚本是一个类似聊天应用程序的php脚本,其工作原理如下:
- php脚本不断地检查data.txt文件,直到它被更改。
- 一旦data.txt被更改,新文本将被输出到网页上。
以下是php脚本:
<?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(500000); // sleep 500ms 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();
?>
我不包括网页代码以保持问题简单。该网页只有一个div,每当data.txt文件更改时,它就会显示data.txt的文本。
我的主要问题点如下:
- 这种循环方法是长轮询服务器的适当方法吗? - 当服务器执行sleep()时,其他同时请求会发生什么? - 有没有任何技术可以减少由于长轮询的连续脚本而对服务器造成的负载? - 如果一个客户端开始这个长轮询请求后断开连接,我们如何知道并相应地停止该断开连接的客户端的脚本?
请指导我解决这个问题...谢谢