<?php
if (isset($_GET['type'] ) && $_GET['type'] === 'EventSource') {
set_time_limit(0); // 必须设置不限制超时,不然输出会被超时截断,导致前端死循环重试
// 设置响应头,指定为 text/event-stream 类型
header('Content-Type: text/event-stream');
// 设置响应头,允许跨域访问
header('Access-Control-Allow-Origin: *');
header('Cache-Control: no-cache');
$filePath = './downTest.txt';//文件(定义你要读取的文件)
$fp=fopen($filePath,"r");
//取得文件大小
$fileSize=filesize($filePath);
$buffer=1024;
$bufferCount=0;
while(!feof($fp) && $fileSize-$bufferCount>0){//循环读取文件数据
$data=fread($fp,$buffer);
$bufferCount+=$buffer;
foreach (mb_str_split($data) as $message) {
// echo $message;
// 发送消息给客户端
echo "data: $message\n\n";
// 刷新输出缓冲并立即发送数据给客户端
ob_flush();
flush();//break;
usleep(125000);
}
}
echo "data: [DONE]\n\n"; // 输出结束
fclose($fp);
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>EventSource - 事件流测试案例</title>
<style>
html,
body {
background: #c7bbbb;
text-align: center;
}
</style>
</head>
<body>
<h1>EventSource - 事件流测试案例</h1>
<div id="myWrap"></div>
</body>
<script type="text/javascript">
let myWrap = document.querySelector('#myWrap');
function streamTest() {
var eventSource = new EventSource("?type=EventSource");
eventSource.onmessage = function (e) {
// console.log(e)
let msg = e.data;
if (msg === "[DONE]") {
eventSource.close();
}
else {
myWrap.textContent+=msg;
}
};
eventSource.onerror = function (e) {
console.log(e);
};
}
</script>
</html>
js事件流案例(php+前端代码)|日常开发笔记
最新推荐文章于 2024-04-12 17:27:57 发布