<?php
header('X-Accel-Buffering: no');
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
set_time_limit(0); //防止超时
ob_end_clean(); //清空(擦除)缓冲区并关闭输出缓冲
ob_implicit_flush(1); //这个函数强制每当有输出的时候,即刻把输出发送到浏览器。这样就不需要每次输出(echo)后,都用flush()来发送到浏览器了
while(1) {
$time = date('Y-m-d H:i:s');
$c = "retry:1000" . PHP_EOL; //重试毫秒数
$c = "event:my_test_message" . PHP_EOL; //定义事件
$c .= "data: The server time is: {$time}" . PHP_EOL; //推送内容
echo $c . PHP_EOL;
sleep(3);
}
<body id="result">
</body>
<script>
var source = new EventSource("sse.php");
source.addEventListener('message', function(event) {
console.log(event)
})
source.addEventListener('my_test_message', function(event) {
console.log(event)
})
</script>