PHP Comet。怎么做得更好? [英] PHP Comet. How to do it better?

查看:90
本文介绍了PHP Comet。怎么做得更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的彗星聊天。
JavaScript使用长轮询发送ajax请求。当服务器在数据库中查找新消息时,它会回答并提供JSON。接下来,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:

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可以抛出exeptions(最长执行时间,有时502 Bad Gateway或Gateway Timeout)。

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).

如何解决?

使用.htaccess和php_value max_execution_time 0?

use .htaccess and "php_value max_execution_time 0"?

或简单地从JavaScript发送新请求,当服务器返回错误时(它使得消息更慢) )?

or simple send new request from JavaScript, when server returns error (it makes getting messages more slow)?

可能,还有其他方法吗?

May be, there is some other way?

推荐答案

如果在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.

这篇关于PHP Comet。怎么做得更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆