PHP实现SSE服务端向客户端推送消息实战代码

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();
?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值