阅读量:0
EventSource 是一种浏览器端的技术,它允许服务器向客户端推送数据。要在 PHP 中实现服务器推送,你需要创建一个 PHP 脚本作为 EventSource 的数据源。以下是一个简单的示例:
- 首先,创建一个名为
server_push.php的 PHP 文件,用于生成服务器推送的数据:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
// 在这里,你可以编写你的业务逻辑,例如从数据库获取数据等
$data = array(
'message' => 'Hello, this is a server-sent event!',
'timestamp' => time()
);
echo "data: " . json_encode($data) . "\n\n";
flush();
// 设置一个延迟,以便演示服务器推送
sleep(5);
?>
- 接下来,创建一个 HTML 文件,例如
index.html,并使用 JavaScript 和 EventSource API 连接到server_push.php:
html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Server-Sent Events Exampletitle>
head>
<body>
<h1>Server-Sent Events Exampleh1>
<div id="messages">div>
<script>
const messages = document.getElementById('messages');
const source = new EventSource('server_push.php');
source.onmessage = function (event) {
const data = JSON.parse(event.data);
const message = document.createElement('p');
message.textContent = `Message: ${data.message}, Timestamp: ${data.timestamp}`;
messages.appendChild(message);
};
source.onerror = function (error) {
console.error('Error: ', error);
};
script>
body>
html>
- 将这两个文件放在你的 Web 服务器上,并通过浏览器访问
index.html。你应该会看到每隔 5 秒钟,服务器向客户端推送一条消息。
注意:确保你的 Web 服务器支持 PHP,并正确配置了 PHP 解释器。
以上就是关于“php eventsource如何实现服务器推送”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm