PHP 彗星。怎样才能做得更好呢?
我有一个简单的彗星聊天。 JavaScript 通过长轮询发送 ajax 请求。当服务器在数据库中发现新消息时,它会应答并给出 JSON。接下来,JavaScript 再次发送请求。
Javascript:
function cometConnect(){
$.ajax({
cache:false,
type:"get",
data:'ts='+ts,
url: urlBack,
async: true,
success: function (arr1) {
//work with JSON
//.....
},
complete:function(){
cometConnect(true);
nerr=false;
},
dataType: "text"
});
}
PHP
$flag=true;
$lastmodif = isset($_GET['ts']) ? $_GET['ts'] : 0;
while($flag){
$q=mysql_query("SELECT text, posterId,modified, fromUserId,toUserId, login FROM commonMessage WHERE modified>$lastmodif");
while($r=mysql_fetch_row($q)){
$flag=false;
//Prepare JSON... variable $resp
//.........
}
usleep(5000);
}
echo $resp;
问题如下:这个“while($flag)”可以执行很长时间(如果没有人发布消息)。因此,Apache 可以抛出异常(最大执行时间,有时是 502 Bad Gateway 或 Gateway Timeout)。
怎么解决呢?
使用 .htaccess 和“php_value max_execution_time 0”?
或者当服务器返回错误时简单地从 JavaScript 发送新请求(这会使获取消息变得更慢)?
或许,还有其他办法吗?
I have a simple comet chat.
JavaScript send ajax request with long polling. When server find new messages in the database, it answers and gives JSON. Next, JavaScript send the request again.
Javascript:
function cometConnect(){
$.ajax({
cache:false,
type:"get",
data:'ts='+ts,
url: urlBack,
async: true,
success: function (arr1) {
//work with JSON
//.....
},
complete:function(){
cometConnect(true);
nerr=false;
},
dataType: "text"
});
}
PHP
$flag=true;
$lastmodif = isset($_GET['ts']) ? $_GET['ts'] : 0;
while($flag){
$q=mysql_query("SELECT text, posterId,modified, fromUserId,toUserId, login FROM commonMessage WHERE modified>$lastmodif");
while($r=mysql_fetch_row($q)){
$flag=false;
//Prepare JSON... variable $resp
//.........
}
usleep(5000);
}
echo $resp;
the problem is following: this "while($flag)" can execute for a long time (if nobody posts messages). So, Apache can throw the exeptions (max execution time, sometimes 502 Bad Gateway or Gateway Timeout).
How to solve it?
use .htaccess and "php_value max_execution_time 0"?
or simple send new request from JavaScript, when server returns error (it makes getting messages more slow)?
May be, there is some other way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该查看 APE 项目。它是一个 Ajax 推送引擎,可能有助于实时通信:www.ape-project.org
You should check out APE Project. It's an Ajax Push Engine, it might help for realtime communication: www.ape-project.org
如果在 40 秒内没有从服务器推送消息,您会从服务器发送一些响应,在此基础上客户端重新请求。
if there are no messages to push from server in say 40 sec, you send some response from server, on the basic of which the client re-request.