使用PHP建立一個SSE

渺小的人类發表於2024-06-29

參考: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);

相關文章