使用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;
?>
調用第三方接口方式
<?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);