使用PHP创建一个SSE

参考:https://www.cnblogs.com/yanweifeng/p/18139827

1.使用PHP创建一个SSE响应来与客户端保持连接

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');

// 模拟数据更新(实际应用中可能是从数据库查询、监控系统获取等)
function generateEventData() {
    $data = [
        'time' => date('Y-m-d H:i:s'),
        'message' => 'This is a server-sent event update.',
    ];
    return 'data: '.json_encode($data)."\n\n";
}

// 无限循环,定期发送更新
while (true) {
    echo generateEventData();
    flush(); // 强制输出缓冲区内容
    ob_flush(); // 清空输出缓冲区
    sleep(5); // 每5秒发送一次更新(可根据实际需求调整间隔)
}

// 如果需要终止连接,可以发送以下注释行并关闭连接
// echo ':event: close';
// exit;
?>
    

 

2.调用第三方接口方式

 

<?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    header('X-Accel-Buffering: no');
    header('Connection: keep-alive');
    set_time_limit(0);
    ob_end_clean();
    ob_implicit_flush(1);
    $url = "";
    $headers = [];
    $params = "";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $data) {
        echo $data;
        return strlen($data);
    });
    curl_exec($ch);
    curl_close($ch);

 

 

 

posted @ 2024-06-29 13:33  流浪2024  阅读(91)  评论(0编辑  收藏  举报