首页 文章

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

提问于
浏览
1

我在我的Web应用程序上实现了server sent eventseventsource . 基本上在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; charset = UTF-8

响应 Headers :

Access-Control-Allow-Origin:* Cache-Control:no-cache连接:Keep-Alive Content-Type:text / event-stream; charset = UTF-8服务器:Apache / 2.4.18(Ubuntu)日期:星期四,格林威治标准时间2002年4月26日20:29:46截止日期:1981年11月19日星期四08:52:00 GMT

请求 Headers :

连接:keep-alive接受:text / event-stream Cache-Control:no-cache

注意:我确认脚本仍在运行日志,并通过检查apache2进程与bash(ps -ax | grep -c apache2)一直在递增 .

1 回答

  • 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开始工作 .

相关问题