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

e0bqpujr  于 2022-10-02  发布在  PHP
关注(0)|答案(4)|浏览(133)

首先,我会说这在我的本地机器上工作得很好,下面的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套接字了),还是有什么我可以做的来解决这个问题?

vql8enpb

vql8enpb1#

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);
}
gc0ot86w

gc0ot86w2#

@derrick,您建议的ob_end_flush();行让我很接近,但在比Hello world代码更复杂的PHP中,我的SSE连接仍然收到不想要的重新打开(我仍然不完全理解ob_end_flush()为什么要这样对我)。下面是我现在使用的模式(其他方面与您的Stream.php相同)。在英语中,我在进入无限循环之前关闭了PHP输出缓冲:

// per http://www.php.net/manual/en/book.outcontrol.php:
//     Clean (erase) the output buffer and turn off output buffering
ob_end_clean();

// how long PHP script stays running/SSE connection stays open (seconds)
set_time_limit(60);
while (true) {

  // use @Derrick's header/send code here

  ob_flush();  // note I don't turn off output buffering here again
  flush();
  sleep(1);
}
50few1ms

50few1ms3#

睡眠阻碍了上交所的上涨。我也有同样的问题。有人建议我使用事件驱动编程。

li9yvcax

li9yvcax4#

只需在Stream.php中的flush()函数之前添加,ob_flush();

更新后的stream.php脚本如下,先观察ob_flush()函数,再观察flush()函数。

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
  **ob_flush();**
    flush();

    // Wait one second.
    sleep(1);
}

相关问题