| |
client.html
<!DOCTYPE html>
<html>
<head>
<title>Server-Sent Events Example</title>
</head>
<body>
<h1>Server-Sent Events Example</h1>
<div id="sse-data"></div>
<script>
// 创建一个 EventSource 对象,连接到服务器端的 SSE
var eventSource = new EventSource('server.php');
// 监听 message 事件,接收来自服务器端的数据
eventSource.addEventListener('message', function (event) {
// 在页面上展示接收到的数据
document.getElementById('sse-data').innerHTML = event.data;
});
</script>
</body>
</html>
server.php
<?php
date_default_timezone_set("America/New_York");
header("Cache-Control: no-store");
header("Content-Type: text/event-stream");
$counter = rand(1, 10);
while (true) {
// 每秒发送一个 "ping" 事件
echo "event: ping\n";
$curDate = date('Y-m-d\TH:i:s');
echo 'data: {"time": "' . $curDate . '"}';
echo "\n\n";
// 在随机时间间隔发送一条简单消息
$counter--;
if (!$counter) {
echo 'data: This is a message at time ' . $curDate . "\n\n";
$counter = rand(1, 10);
}
// 刷新输出缓冲区
if (ob_get_level() > 0) {
ob_end_flush();
}
flush();
// 如果客户端中断连接(关闭页面),则跳出循环
if (connection_aborted()) break;
sleep(1);
}
系列课程并未全部上架,处于先行测试阶段