服务器发送事件工作,但有很长的时间延迟

Goo*_*bye 7 php apache server-sent-events

我开始说这在我的本地机器上完美运行,下面的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);
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

上传到live dev之后我确实预计会有一点延迟.服务器.但是有大约15到20分钟的时间延迟.在我看到第一个条目之前.

连接不会丢失.(问题.已经过了40分钟+现在.)这只是一个Apache循环问题(意味着是时候查看网络套接字)还是我可以做些什么来解决这个问题?

Goo*_*bye 9

Server.php需要如下:

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 "Event: server-time" . PHP_EOL;
    print "data: " . date( 'G:H:s', time() ) . PHP_EOL;
    print PHP_EOL;

    ob_end_flush();     // Strange behaviour, will not work
    flush();            // Unless both are called !

    // Wait one second.
    sleep(1);
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你。虽然“ob_flush()”和“flush()”的组合对我不起作用,但添加“ob_end_flush()”却可以。 (2认同)