我的代码应该每秒从服务器向客户端发送一个事件(我应该会在Firefox的控制台中看到它们每隔一段时间就会出现)。但我同时参加了所有五项活动。为什么?
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();
?>
我正在使用Ubuntu 14.04和Apache,如果这很重要的话。
我在MDN中发现了一个例子,它使用与您的php代码相似的php代码,但有一点不同,它调用ob_end_flush()
。