在 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 文件。