由於有一個需求,需要把一些統計數據實時顯示在web上,不需要考慮瀏覽器兼容性。找了一圈之後,有客戶端輪詢式的ajax,有高大上的websocket,html5的SSE(SERVER-SENT EVENTS 服務端發送事件)感覺實現起來比較簡單。
首先找到了這篇文章《PUSHING UPDATES TO THE WEB PAGE WITH HTML5 SERVER-SENT EVENTS》,根着它做,準備好兩個文件:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="serverData">Here is where the server sent data will appear</div>
<script type="text/javascript">
//check for browser support
if (typeof (EventSource) !== "undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("send_sse.php");
//detect message receipt
eSource.onmessage = function (event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
};
} else {
document.getElementById("serverData").innerHTML = "Whoops! Your browser doesn't receive server-sent events.";
}
</script>
</body>
</html>
send_sse.php
<?php
//streaming code
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
//generate random number for demonstration
$new_data = rand(0, 1000);
//echo the new number
echo "data: New random number: $new_data\n\n";
flush();
?>
放到支持PHP的apache2服務器上,用chrome和firefox訪問得到結果是,每隔一個固定的時間,大概4秒吧,會更新顯示一次隨機數,查看F12如下圖所示。
什麼?!說好的由服務端主動推送數據呢?
上面的圖看起來仍舊是客戶端(瀏覽器)每隔一定的時間去刷新服務端數據啊!而且這個時間間隔還是固定的沒有任何地方可以設置,離介紹說的服務端有數據就推送給瀏覽器然後由瀏覽器負責顯示相去甚遠。
事情應該沒有那麼簡單的。再找文章,這次找到這篇文章《html5之sse服務器發送事件EventSource介紹》
根據文章,修改了服務端代碼如下:
send_sse.php
<?php
//streaming code
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
while(1){
//generate random number for demonstration
$new_data = rand(0, 1000);
//echo the new number
echo "data: New random number: $new_data\n\n";
ob_flush();
flush();
$delay = rand(1,10);
usleep($delay * 100000);//隨機延遲100毫秒到1秒
}
?>
刷新index.html頁面,這次對了,數據更新有時快有時慢(在100毫秒和1秒之間),而且客戶端不會一次一次去連接服務端,而是保持着一個長時間的連接,F12如下圖所示: