在 PHP 中實現 event-stream,可以使用 Server-Sent Events (SSE)
sse.php
),并設置正確的頭信息以啟動 event-stream:<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no'); // 對于 Nginx 服務器
// 生成事件數據
function send_message($id, $data, $event = '') {
echo "id: $id" . PHP_EOL;
if ($event != '') {
echo "event: $event" . PHP_EOL;
}
echo "data: $data" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
$serverTime = time();
send_message($serverTime, 'Hello, this is a message from the server!');
// 模擬事件流
for ($i = 0; $i < 10; $i++) {
sleep(1);
$serverTime = time();
send_message($serverTime, 'This is message ' . ($i + 1));
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event Stream Example</title>
</head>
<body>
<ul id="event-log"></ul>
<script>
const eventSource = new EventSource('sse.php');
eventSource.onmessage = function (event) {
const data = JSON.parse(event.data);
const listItem = document.createElement('li');
listItem.textContent = `Message ID: ${data.id}, Message: ${data.message}`;
document.getElementById('event-log').appendChild(listItem);
};
eventSource.onerror = function (error) {
console.error('Error occurred:', error);
};
</script>
</body>
</html>
注意:確保您的 Web 服務器支持 PHP,并已正確配置。同時,確保在 JavaScript 代碼中使用正確的路徑來引用 PHP 文件。