Ob_end_flush 不断产生错误

Ob_end_flush is generating constant errors

我目前正在处理服务器发送的事件,但遇到了一个奇怪的问题。随着事件的进行,每次迭代我都会收到以下错误:

ob_end_flush(): failed to delete and flush buffer. No buffer to delete or flush in

我的服务器事件服务器端代码如下:

<?php

  require "connect.php";

  session_write_close();

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

  $savedcount = 0; 
  while (1) {

    // Who's mechanism 
    $query = $mysqli->query("SOME QUERY"); 
    $rowcount = $query->num_rows;

    if ($savedcount != $rowcount) {
       // echo stuff
       $savedcount = $rowcount; // only echo stuff if there is new content
    }

    ob_end_flush();
    flush();
    sleep(2);
  }

?>

我不完全理解缓冲区。此外,在您认为这是糟糕的做法之前,请知道服务器发送的事件是特殊的。这是他们在 MDN 上显示的类似脚本。出于这个原因,我不确定为什么我不断收到这些错误。

建议?

在 PHP 中,输出缓冲区保存将打印到页面的实际内容 - 基本上是回显或打印的任何内容。所以在你什么都不回显的情况下,缓冲区将是空的,当你尝试用 ob_end_flush 发送任何内容时你会得到一个错误。您可以添加一个检查来避免此错误:

if (ob_get_length() > 0) {
    ob_end_flush();
    flush();
}

sleep(2);

我一直用这个成语:

@ob_flush();@flush();

引用 HTML5 SSE 的数据推送应用程序第 21 页:(免责声明:我的书)

@ is said to be slow. But putting that in context, it adds on the order of 0.01ms to call it twice, as shown here. ... http://git.php.net/?p=php-src.git;a=blob;f=sapi/apache2handler/sapi_apache2.c#l290 suggests flush() can never throw an error, so @ on flush() could be dropped, just leaving it on @ob_flush().

http://git.php.net/?p=php-src.git;a=blob;f=main/output.c#l1328显示ob_flush()可以给出的两个E_NOTICEs。