简体   繁体   中英

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). But I get all five events at once. Why?

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:

<?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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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