服务器发送的事件轮询导致长时间延迟

Server-Sent Events Polling causing long delays

我有一个连接器可以使用 cURL 和 PHP.

调用 RESP API

我需要每秒调用一个方法来检查新消息然后处理它们。我使用以下两种方法来处理消息

  1. AJAX轮询使用SetInterval():每秒调用一次php脚本。这非常有效,除了我无法同时从浏览器的不同选项卡中阻止 运行 中的多个 SetInterval()。 (我不想让用户打开 10 个浏览器选项卡,导致一个用户同时拥有 10 个 SetInterval() 是 运行。
  2. Server Sent Events using EventSource: 一旦队列中有新数据,服务器将发送更新给浏览器。这会减慢响应时间。我对脚本进行的每次调用都需要大约 20 多秒才能完成,这是一个问题。我不确定为什么会这样。

这是我的SetInterval()实现

function startCalls(){
    //update the screen using Intervals
    refreshIntervalId = setInterval(function() {

        $.getJSON("index.php", {'method': 'getMessages', 'jSON': true} , function(data){
            processServerData(data);
         });

    }, 1000);
}

一旦用户登录我就调用这个函数startCalls()

在 index.php 文件中我有这段代码被调用

if($method == 'getMessages'){

    $messaging = new ICWS\Messaging($icws);
    $messaging->processMessages();
    $myQueue = $messaging->getCallsQueue();
    echo json_encode($myQueue );

}

这是我的第二个实现"Server-Sent Events"

//Server Side Message Polling
function startPolling(evtSource){

    evtSource.addEventListener("getMessagingQueue", function(e) {

        var data = JSON.parse(e.data);
        processServerData(data)
    }, false);
}

一旦用户登录我就调用这个函数startPolling( new EventSource("poll.php") );

为了简单起见,假设我的 processServerData 方法如下所示

function processServerData(data){
    console.log('process the data received from the server');
}

这是我的 php 代码

<?php

    require 'autoloader.php';

    //Make sure cURL is enabled on the server
    if(!is_callable('curl_init')){
        exit('cURL is disabled on this server. Before making API calls cURL extension must be enabled.');
    }

    if( isset($_COOKIE['icws_username']) ){
        $user = trim($_COOKIE['icws_username']);
    }

    if( isset($_COOKIE['icws_password']) ){
        $pass = trim($_COOKIE['icws_password']);
    }

    if( isset($_COOKIE['icws_station']) ){
        $stationName = trim($_COOKIE['icws_station']);
    }

    if( !isset($user, $pass, $stationName) ){
        echo json_encode(array('status' => 'The IC credentials you entered are invalid')); 
        exit;
    }

    $scheme = 'http';
    $host   = 'host';
    $port   = '8018';
    $sleepTime = 1;
    $url = sprintf('%s://%s:%s@%s:%s', $scheme, $user, $pass, $host, $port);

    try {
        header("Content-Type: text/event-stream\n\n");
        session_start();

        //configure the connection
        $conf = new ICWS\Config\Config($url, $stationName); 

        //create a new instance of icws
        $attrebutes = array();
        $icws = new ICWS\Connection($conf, $attrebutes, true); 

        $messaging = new ICWS\Messaging($icws);

    ob_end_clean();
    while(true){

        header("Content-Type: text/event-stream" . PHP_EOL);
        header("Cache-Control: no-cache" . PHP_EOL);

        $messaging->processMessages();
        $result = $messaging->getCallsQueue();

        //$current = $icws->getCurrentUserStatusQueue();
        echo 'event: getMessagingQueue' . PHP_EOL;
        echo 'data: ' . json_encode( $result) . PHP_EOL;    
        echo PHP_EOL; //required  

        ob_end_flush();
        flush(); 
        sleep(1);

    }

    } catch(Exception $e){
        echo $e->getMessage();
    }


?>

服务器似乎锁定了所有到达服务器的请求,直到无限循环被 "page refresh" 停止,只要我刷新页面,其他请求就会立即处理

为什么 Server-Sent Event 会导致这样的问题?

不同类型极化的重要资源can be found in this Question

一切看起来都很稳健,所以我猜测您正受到会话锁定的影响。 PHP 会话锁定会话文件,这样一次只有一个 PHP 脚本可以使用会话;仔细想想,这是个好主意!

会话和 SSE 的问题是 SSE PHP 永远处理 运行s,因此它永远锁定会话。如果任何其他 PHP 脚本尝试在同一会话中 运行,它将阻塞(我相信在 session_start() 调用时)。

这在主题上看起来像 a good article;建议是在您知道不再需要会话时致电 session_write_close()。例如。如果您只需要使用会话来检查他们之前是否已授权自己,那么您可以直接调用 session_write_close(),其他进程将不会被阻止。