PHP实现SSE服务端向客户端推送消息实战代码,虽然websocket也可以实现,但是感觉大材小用。好像很多大模型也都是采用sse技术实现数据推送的。研究了下还挺好玩的。
html代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>诗句推送</title>
<style>
body {
font-family: 'Microsoft YaHei', sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
h1 {
color: #333;
text-align: center;
}
#poem-container {
background-color: white;
border-radius: 5px;
padding: 20px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
min-height: 200px;
}
.poem-line {
margin-bottom: 10px;
font-size: 18px;
line-height: 1.6;
color: #333;
}
.timestamp {
color: #999;
font-size: 12px;
margin-left: 10px;
}
</style>
</head>
<body>
<h1>诗句推送</h1>
<div id="poem-container"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const poemContainer = document.getElementById('poem-container');
// 创建 SSE 连接
const eventSource = new EventSource('poem_sse.php');
// 监听消息事件
eventSource.addEventListener('message', function(event) {
const data = JSON.parse(event.data);
const lineElement = document.createElement('div');
lineElement.className = 'poem-line';
lineElement.innerHTML = data.line + '<span class="timestamp">' + new Date().toLocaleTimeString() + '</span>';
poemContainer.appendChild(lineElement);
});
// 监听错误事件
eventSource.addEventListener('error', function(event) {
console.error('SSE 连接错误:', event);
eventSource.close();
// 尝试重新连接
setTimeout(function() {
location.reload();
}, 5000);
});
});
</script>
</body>
</html>
后端代码
<?php
// 设置响应头,指定内容类型为 text/event-stream
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no'); // 禁用 Nginx 缓冲
// 禁用 PHP 输出缓冲
if (ob_get_level()) ob_end_clean();
// 一首诗的内容
$poem = [
"床前明月光,",
"疑是地上霜。",
"举头望明月,",
"低头思故乡。"
];
// 发送 SSE 消息的函数
function sendSSEMessage($data) {
echo "data: " . json_encode($data, JSON_UNESCAPED_UNICODE) . "\n\n";
flush();
}
// 为每一行诗句发送 SSE 消息
foreach ($poem as $index => $line) {
// 第一行立即发送,后续行每隔一分钟发送一次
if ($index > 0) {
sleep(2); // 等待 60 秒
}
sendSSEMessage(['line' => $line]);
}
// 发送完所有诗句后,发送一个结束消息
sendSSEMessage(['line' => '——李白《静夜思》']);
// 关闭连接
exit();
?>