PHP SSE实时推流 apache服务不能实时推流问题
时间:2024-11-14 10:55 作者:wen 分类: 无
重要: 需要开启HTTPS, 需要开启HTTPS, 需要开启HTTPS
<?php
// 关闭输出缓存
// ini_set('zlib.output_compression', 'Off'); // 关闭gzip压缩
// 设置响应头
header('Content-Type: text/event-stream'); // 告诉浏览器,这是一个服务器推送事件
header('Cache-Control: no-cache'); // 告诉浏览器不要缓存
header('Connection: keep-alive'); // 保持长连接
header('X-Accel-Buffering: no'); // 关闭Nginx的gzip压缩
header('Content-Encoding: none'); // 关闭gzip压缩
// 禁用输出缓冲
ob_implicit_flush(true);
ob_end_clean(); // 清除现有的输出缓冲
for ($i = 0; $i < 5; $i++) {
// 模拟服务器推送数据
$data = array(
'text' => 'Hello World!',
);
returnEventData($data);
// 确保每个事件之间有换行
flush(); // 强制输出缓冲区内容
sleep(1); // 模拟数据推送延迟
}
returnEventData("done");
function returnEventData($returnData, $event = 'message', $id = 0, $retry = 1000)
{
$str = '';
if ($id > 0) {
$str .= "id: {$id}\n";
}
if ($event) {
$str .= "event: {$event}\n";
}
if ($retry > 0) {
$str .= "retry: {$retry}\n";
}
if (is_array($returnData)) {
$returnData = json_encode($returnData);
}
$str .= "data: {$returnData}\n\n";
echo $str;
}
标签: PHP基础