首先,我会说这在我的本地机器上工作得很好,下面的js示例连接到Stream.php,并每秒接收服务器当前时间的持续更新。
index.php
var source = new EventSource("stream.php");
source.addEventListener('message', function(e) {
console.log(e);
}, false);
source.addEventListener('open', function(e) {
console.log(e);
}, false);
source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
console.log('closed');
}
}, false);
Stream.php
while(true)
{
// Headers must be processed line by line.
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// Set data line
print "data: " . date( 'G:H:s', time() ) . PHP_EOL . PHP_EOL;
// Toilet
flush();
// Wait one second.
sleep(1);
}
我确实预料到在上传到实时开发人员后会有一点延迟。伺服器。但会有大约15到20分钟的时间延迟。甚至在我看到第一个条目之前。
连接不会断开。(探测。已经开了40分钟了。+现在。)这只是一个Apache循环问题(这意味着是时候看看Web套接字了),还是有什么我可以做的来解决这个问题?
4条答案
按热度按时间vql8enpb1#
Server.php需要如下所示:
Stream.php
gc0ot86w2#
@derrick,您建议的
ob_end_flush();
行让我很接近,但在比Hello world代码更复杂的PHP中,我的SSE连接仍然收到不想要的重新打开(我仍然不完全理解ob_end_flush()
为什么要这样对我)。下面是我现在使用的模式(其他方面与您的Stream.php相同)。在英语中,我在进入无限循环之前关闭了PHP输出缓冲:50few1ms3#
睡眠阻碍了上交所的上涨。我也有同样的问题。有人建议我使用事件驱动编程。
li9yvcax4#
只需在Stream.php中的flush()函数之前添加,ob_flush();
更新后的stream.php脚本如下,先观察ob_flush()函数,再观察flush()函数。