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

时间:2018-04-26 20:50:44

标签: php server-sent-events php-7.1 event-stream

我已在我的网络应用程序中使用server sent events实施了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”标题应该会自动关闭连接,但在我的情况下却不然。

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

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

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

响应标题:

  

Access-Control-Allow-Origin:*

     

缓存控制:无缓存

     

连接:Keep-Alive

     

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

     

服务器:Apache / 2.4.18(Ubuntu)

     

日期:2018年4月26日星期四20:29:46 GMT

     

Expires:Thu,1981年11月19日08:52:00 GMT

请求标题:

  

连接:保持活力

     

接受:text / event-stream

     

缓存控制:无缓存

注意:我确认脚本仍在运行日志,并检查apache2进程和bash(ps -ax | grep -c apache2),这些进程总是递增。

1 个答案:

答案 0 :(得分:0)

感谢@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();
       }
    }

connection_aborted开始工作。