使用 HTML5 服务器发送事件的即时简单 PHP 通知
sse.php
<?php
$dbconn = new PDO("pgsql:host=localhost;dbname=mydb", "pduser", "userpass");
$dbconn->exec('LISTEN "channel_name"'); header("X-Accel-Buffering: no"); header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
ob_end_flush(); $inc=0;
while (1) {
$result = "";
$result = $dbconn->pgsqlGetNotify(PDO::FETCH_ASSOC, 10000);
if ( $result ) {
echo "id: $inc\ndata: ".stripslashes(json_encode($result))."\n\n";
$inc++;
}
flush();
}
?>
在 Mozilla 网站(ssedemo.php)上测试了 HTML+JS 示例文件