PHP 服务器发送的事件连接不会关闭?

PHP Server Sent Events Connection won't close?

我已经在我的 Web 应用程序上实现了 server sent events with eventsource。 基本上在 javascript 我的代码看起来像:

    var myEventSource;
    if (typeof(EventSource) !== "undefined" && !myJsIssetFunction(viridem.serverSideEvent.config.reindexProcessingEvent)) {
        myEventSource = new EventSource('/my/url/path.php?event=myevent');
        EventSource.onmessage = function(e) {
          [...] //Dealing with e.data that i received ...
        }
    }

在PHP这边,我有这样的东西:

<?php
  header('Content-Type: text/event-stream');
  header('Cache-Control: no-cache');
  header("Access-Control-Allow-Origin: *");

  //this or set_the_limit don't work but whatever I can deal without it
  ini_set('max_execution_time', 300);
  //ignore_user_abort(true); tried with true and false

  bool $mustQuit = false;

  while (!$mustQuit && connection_status() == CONNECTION_NORMAL) {
     if(connection_aborted()){
      exit();
     }
     [...] //doing some checkup

    if ($hasChange) {
      //Output stuffs
      echo 'data:';
      echo json_encode($result);
      echo "\n\n";
      ob_flush();
      flush();
      sleep(5);
    }

  }

根据在 PHP Event Source keeps executing 找到的答案,"text/event-stream" headers 应该使连接自动关闭,但在我的情况下不会..

我确实在 window.onbeforeunload 事件中添加了一个 eventsource.close 但它没有关闭事件。

window.onbeforeunload =  function() {
    myEventSource.close();
    myEventSource = null;
};

如果我查看浏览器的网络部分,我可以看到 Headers 是(在添加最大循环 30 之后): Content-Type: text/event-stream;字符集=UTF-8

响应Headers:

Access-Control-Allow-Origin: *

Cache-Control: no-cache

Connection: Keep-Alive

Content-Type: text/event-stream;charset=UTF-8

Server: Apache/2.4.18 (Ubuntu)

Date: Thu, 26 Apr 2018 20:29:46 GMT

Expires: Thu, 19 Nov 1981 08:52:00 GMT

请求Headers:

Connection: keep-alive

Accept: text/event-stream

Cache-Control: no-cache

注意:我确认脚本仍然是 运行 日志,并通过使用 bash (ps -ax | grep -c apache2) 检查总是递增的 apache2 进程。

感谢@LawrenceCherone 的帮助,我确实发现您需要“输出数据”才能使 connection_aborted 工作...

在我的例子中,我只在需要时才输出数据...

通过添加

   if ($hasChange) {
      //Output stuffs
      echo 'data:';
      echo json_encode($result);
      echo "\n\n";
      ob_flush();
      flush();
      sleep(5);

    } else {
       echo 'data:';
       echo "\n\n";
       ob_flush();
       flush();
       if(connection_aborted()){
         exit();
       }
       sleep(5);
    }

connection_aborted 开始工作了。