简体   繁体   English

HTML5 服务器发送的事件不是实时的?

[英]HTML5 Server-Sent Events not real time?

My code is supposed to send one event each second from the server to the client (I should see them coming at regular intervals in the Firefox's console).我的代码应该每秒从服务器向客户端发送一个事件(我应该在 Firefox 的控制台中看到它们定期发送)。 But I get all five events at once.但我一次得到所有五个事件。 Why?为什么?

adm.php: adm.php:

<html>
<head>
<script type='text/javascript'>
var evtSource;
function btnClick() {
    evtSource = new EventSource('adm_sse.php');
    evtSource.onmessage = function(e) {
        console.log(e.data);
        if (e.data == 'end') {
            evtSource.close();
        }
    };
}
</script>
</head>
<body>
    <button type='button' onclick='btnClick()'>Test SSE</button>
</body>
</html>

adm_sse.php: adm_sse.php:

<?php
header("Content-Type: text/event-stream");
//header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
for ($i=0; $i<5; $i++) {
    echo "data: $i (".date('d/m/Y H:i:s').")\n\n";
    flush();
    sleep(1);
}
echo "data:end\n\n";
flush();
?>

I'm using Ubuntu 14.04 with Apache, if that matters.如果这很重要,我正在将 Ubuntu 14.04 与 Apache 一起使用。

在 MDN 中找到了一个示例,它使用与您类似的 php 代码,但有一点不同,它调用ob_end_flush()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM