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()来发送到浏览器了
//发送消息
$data
= 0
;
while
(
true
)
$data
++
;
$c
= "event:test" .
PHP_EOL
;
//
定义事件
$c
.= "data: " .
$data
.
PHP_EOL
;
//
推送内容
echo
$c
.
PHP_EOL
;
sleep
(1
);
浏览器端代码:
<!DOCTYPE html>
<html lang="zh-CN">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="renderer" content="webkit">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SSE 测试</title>
<link href="https://lib.baomitu.com/normalize/latest/normalize.min.css" rel="stylesheet">
<style>
/* css style */
body{
padding:0 10px;
</style>
<script src="https://lib.baomitu.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<!-- 内容 -->
<h1>SSE 测试</h1>
<div id="divInfo"></div>
<script>
$(function(){
// JS
function showInfo(str)
$('#divInfo').append('<div>' + str + '</div>');
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("sse.php");
//监听test事件
source.addEventListener('test', function (event) {
showInfo(event.data)
} else {
showInfo("您的浏览器不支持SSE");
</script>
</body>
</html>