木子屋 Dnawo's BLOG

SSE服务器端单向实时给客户端推送消息示例(PHP版)

👤 dnawo 📅 2026-11-18 👁 14 👍 0 💬 0 🔄 本站原创 📂 Web编程
Index.html:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>SSE 示例</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 20px; }
    #status { color: #888; margin-bottom: 10px; }
    li { padding: 4px 0; border-bottom: 1px dashed #eee; }
  </style>
</head>
<body>
  <h3>SSE 实时消息</h3>
  <div id="status">未连接</div>
  <ul id="list"></ul>

  <script>
    const statusEl = document.getElementById('status');
    const listEl   = document.getElementById('list');

    // 打开连接(可带参数)
    const es = new EventSource('sse.php?name=小明');

    // 连接建立
    es.onopen = () => {
      statusEl.textContent = '✅ 已连接';
    };

    // 默认 message 事件
    es.onmessage = (e) => {
      const data = JSON.parse(e.data);
      const li = document.createElement('li');
      li.textContent = `[${data.time}] #${data.id} ${data.msg}`;
      listEl.appendChild(li);
    };

    // 自定义 close 事件:服务端推送完毕
    es.addEventListener('close', (e) => {
      statusEl.textContent = '🔚 服务端已结束推送';
      es.close(); // 主动关闭,否则浏览器会自动重连
    });

    // 错误处理
    es.onerror = (e) => {
      console.error('SSE 出错', e, 'readyState =', es.readyState);
      if (es.readyState === EventSource.CLOSED) {
        statusEl.textContent = '❌ 连接已关闭';
      } else {
        statusEl.textContent = '⚠️ 连接中断,正在重连…';
      }
    };
  </script>
</body>
</html>

sse.php:

<?php
// sse.php —— SSE 服务端
header('Content-Type: text/event-stream; charset=utf-8');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no'); // 关键:关闭 Nginx 缓冲

// 关闭所有 PHP 输出缓冲
while (ob_get_level() > 0) {
    ob_end_flush();
}
ob_implicit_flush(true);
ini_set('zlib.output_compression', '0');

set_time_limit(0);          // 不限制脚本执行时间
ignore_user_abort(true);    // 客户端断开后脚本不要立刻退出

// 如果用到 session,一定要在长连接开始前释放,否则会阻塞其他请求
// session_start();
// session_write_close();

// 接收前端参数(可选)
$name = $_GET['name'] ?? '访客';

// 自定义重连间隔(毫秒),浏览器断线后会按此时间重连
echo "retry: 3000\n\n";
flush();

$id = 0;
while (true) {
    // 客户端关闭连接则退出
    if (connection_aborted()) {
        break;
    }

    $id++;
    $payload = [
        'id'   => $id,
        'time' => date('H:i:s'),
        'msg'  => "你好 {$name},这是第 {$id} 条推送",
    ];

    // SSE 消息格式:字段名: 值\n,一条消息以空行结束
    echo "id: {$id}\n";
    echo "event: message\n";
    echo "data: " . json_encode($payload, JSON_UNESCAPED_UNICODE) . "\n\n";
    flush();

    // 推送 10 条后结束
    if ($id >= 10) {
        echo "event: close\n";
        echo "data: " . json_encode(['msg' => '推送结束'], JSON_UNESCAPED_UNICODE) . "\n\n";
        flush();
        break;
    }

    sleep(1); // 模拟每秒产生一条数据
}

常见问题

问:怎么在IIS服务器上内容是一次性输出的?
答:这通常是IIS响应缓冲机制导致的,在web.config中将响应缓冲区大小设置为0即可:
<system.webServer>
    <handlers>
        <add name="php-8.5" 
             path="*.php" 
             verb="GET,HEAD,POST" 
             modules="FastCgiModule" 
             scriptProcessor="C:\PHP\php-cgi.exe" 
             resourceType="Either" 
             requireAccess="Script" 
             responseBufferLimit="0" />
    </handlers>
</system.webServer>

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 短轮询、长轮询、SSE和WebSocket四种前后端通信方式比较