我有这段代码(它使用服务器端事件,但问题是刷新不起作用):
<?php
class Events {
function __construct($fn, $options=array()) {
$settings = array_merge(array(
'headers' => array(
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'no-cache',
'Connection' => 'keep-alive'
),
'retry' => 2000
), $options);
foreach($settings['headers'] as $header => $value) {
header("$header: $value");
}
$lastId = intval(isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? $_SERVER["HTTP_LAST_EVENT_ID"] : 0);
echo ":" . str_repeat(" ", 2048) . "\n";
echo "retry: " . $settings['retry'] . "\n";
$id = $lastId;
$i = 0;
foreach ($fn($id) as $value) {
echo "id:" . $id++ . "\n";
echo "data: " . $value . "\n\n";
ob_flush();
flush();
if ($i++ == 10) {
break;
}
}
}
}
if (isset($_SERVER['HTTP_ACCEPT']) && preg_match("%text/event-stream%", $_SERVER['HTTP_ACCEPT'])) {
new Events(function($id) {
while(true) {
$array = array("Foo", "Bar", "Baz", "Quux");
yield json_encode(array("message" => $array[array_rand($array)]));
sleep(1);
}
});
} else { ?><!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Leash</title>
<meta name="Description" content=""/>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
var source = new EventSource("/EventSource.php");
source.addEventListener("message", function(message) {
console.log(JSON.parse(message.data).message);
});
</script>
<body>
<textarea></textarea>
</body>
</html><?php } ?>
它在 wamp 服务器上本地工作,但不在我的共享主机上,我在 php 信息中有这个:
Server API CGI/FastCGI
Directive Local Value Master Value
output_buffering 4096 4096
而且我无法更改它,我也尝试将其添加ob_start()
到我的脚本中ini_set('output_buffering', 0)
并删除ob_flush
,但这没有帮助。
我还尝试在 .user.ini 中为目录将 output_buffering 设置为 0,并且 php 信息显示 Local Value 为 0 但服务器端事件仍然不起作用,我一次获得所有事件,开发人员工具(pending)
说空类型,直到它在 10 秒后完成。
有人知道如何解决这个问题吗?
编辑:
我再次尝试运行代码(几年后在 Fedora/Linux 上),但它给出了相同的结果。Gzip 未打开,但消息显示在最后。
我试过了:
- 添加标题
'X-Accel-Buffering' => 'no'
- 还添加
echo "event:". $event ."\n";
没有成功。
我正在查看使用 while 循环时未加载服务器端 PHP 事件页面,但解决方案不起作用,代码给出与 OP 相同的错误(他没有太多代表,所以他可能在 SO 上不活跃),我的至少显示了事件,但我打破了循环,他的代码有无限循环。
这是服务器(Fedora)发送的标头:
Cache-Control: no-cache
Connection: keep-alive, Keep-Alive
Content-Type: text/event-stream;charset=UTF-8
Date: Tue, 17 Sep 2019 07:40:44 GMT
Keep-Alive: timeout=5, max=92
Server: Apache/2.4.41 (Fedora) OpenSSL/1.1.1c
Transfer-Encoding: chunked
X-Accel-Buffering: no
X-Powered-By: PHP/7.2.22
同样的情况也发生在来自http://demo.howopensource.com/sse/的简单代码上
我的 php.ini 有这个:
$ grep -E 'user_ini|output_buffer|zlip.' /etc/php.ini | grep -v '^;'
user_ini.filename = ".user.ini"
output_buffering = 4096
所以我也试过,设置.user.init
文件:
output_buffering = 0
和
output_buffering = Off
但它也没有奏效。脚本正在等待立即返回所有内容。本文中的代码Streaming PHP - 在 PHP、Apache、Nginx 和 Varnish 中禁用输出缓冲如果我$string_length = 4096;
甚至使用那个 phpinfo 表示该目录在本地禁用了输出缓冲。
编辑2:
它似乎刷新在我的共享主机上工作,https://jcubic.pl/01.php?size=100但我无法在 Fedora 上本地测试它,因为刷新不起作用。
这是我本地 phpinfo 输出的链接:https ://jcubic.pl/phpinfo().html