【问题标题】:How to Improve the Long Poll Capabilities Using PHP and AJAX如何使用 PHP 和 AJAX 提高长轮询能力
【发布时间】:2014-06-24 11:21:51
【问题描述】:

我已经使用普通的 Apache 服务器、PHP、AJAX 和 Javascript 成功实现了长轮询。我不使用 Jquery 与服务器通信。

问题是 Apache 服务器功能有限,服务器无法提供超过 5 个浏览器选项卡。

我想知道是否对 Apache 或 PHP 进行了任何自定义以使它们处理更多的并发连接?或者是否有任何新的/智能技术可以做到这一点?专门用于长轮询的强大 Web 服务器可以处理的最大线程数是多少?

由于浏览器的兼容性,我对 Web Sockets 不感兴趣。我需要一些简单而健壮的PHP。脸书在做什么?我想知道他们如何处理数百万用户的所有动态更新!他们使用什么产品/技术?

我的代码示例:

srv_polling.php

<?php
function getResults(){..... return result;}

// recursive function inside the server 
function hasResultChanged($old,$timeStart){

    // to avoid server timeout (in seconds) in case no change for results
    if(round(abs(time() - $timeStart) / 60*60,2) > 50)
        return;

    $new = getResults();

    if($new != $old)    // get back to browser
        return true;
    else{
        $old = getResults();
        sleep(2);
        return $hasResultChanged($old,$timeStart);

    }
}

$timeStart = time();
$old  = $getResults();
sleep(2);
$hasResultChanged($old,$timeStart);

?>

// Javascript code to be executed at browser end
alert('Result has changed');

// Send AJAX request again to same page(srv_polling.php):
ajax.call({......})

感谢您的提示!非常感谢。

【问题讨论】:

    标签: php ajax apache long-polling


    【解决方案1】:

    我在我的项目中使用它

    public function getLPollData($user, $handlerName) {
        set_time_limit (600);
        date_default_timezone_set('Europe/Berlin');
        $counterEnd = (int)$_REQUEST["counterEnd"];
        $counterStart = (int)$_REQUEST["counterStart"];
        $this->expireNotifications($counterStart, $counterEnd);
        $secCount = IDLE_WAIT;
        do {
            sleep(IDLE_TIME);
            $updates = $this->fetchAllNotifications($counterEnd);
        } while (!$updates && ($secCount--)>0);
    
        if($updates){
    
        }
    
        header("HTTP/1.0 200");
        return sprintf ('{"time" : "%s", "counter" : "%d", start : %d, data : %s}'
                , date('d/m H:i:s'), $counterEnd,$counterStart,json_encode($updates));
    }
    

    IDLE_WAIT 和 IDLE_TIME 的组合(10*3=~30 秒)。

    但我认为您的问题不在服务器端,如果您从浏览器打开 5-6 个连接,请记住每个浏览器一次对某个特定域的活动连接数有限制。尝试差异浏览器或更好的差异机器,一个浏览器中最多两个选项卡。

    【讨论】:

      猜你喜欢
      • 2011-01-06
      • 2012-04-15
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      相关资源
      最近更新 更多