Nae*_*hab 5 javascript php ajax comet long-polling
首先,我要感谢所有伟大的人,因为他们对新程序员非常有帮助.
我有一个关于长轮询的问题.我研究了一些关于Comet Programming的长轮询技术的文章.这个方法对我来说似乎很难,因为它有时也需要在服务器端安装一些脚本.
现在我找到了一个关于长轮询的例子.它工作得很好,但我不确定它是否是正确的方法.示例脚本是关于类似聊天的应用程序.这个PHP脚本的工作原理如下:
这是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();
?>
Run Code Online (Sandbox Code Playgroud)
我不包括网页代码以保持问题简单.网页只有一个div,它会在每次更改时显示data.txt的文本.
我的问题的要点是:
sleep();其他同时请求时会发生什么?请指导我解决这个问题...谢谢
是的,这是个主意.您应该记住,此脚本不会结束,并且将为每个用户生成一个PHP实例.我正在使用带有v8cgi服务器端的longpoll逻辑.客户端启动XMLHttp请求(XHR)后,服务器开始检查新输入的间隔.我添加了一个计时器服务器端,每5分钟发送一次响应,之后客户端 - 如果没有断开连接 - 重新发送XHR并重复该过程.
因此,服务器端机制的每个实例最多运行不超过5分钟,因为如果客户端断开连接,服务器在5分钟后发送的响应不会跟随新的XHR.
过程如下:
| 归档时间: |
|
| 查看次数: |
1027 次 |
| 最近记录: |