HTML5 服務(wù)器發(fā)送事件(Server-Sent Events)
HTML5?服務(wù)器發(fā)送事件(Server-Sent Events)
HTML5 服務(wù)器發(fā)送事件(server-sent event)允許網(wǎng)頁獲得來自服務(wù)器的更新。
瀏覽器支持?
所有主流瀏覽器均支持服務(wù)器發(fā)送事件,除了 Internet Explorer。
Server-Sent 事件 - 單向消息傳遞
Server-Sent 事件指的是網(wǎng)頁自動獲取來自服務(wù)器的更新。
以前也可能做到這一點,前提是網(wǎng)頁不得不詢問是否有可用的更新。通過服務(wù)器發(fā)送事件,更新能夠自動到達(dá)。
例子:Facebook/Twitter 更新、估價更新、新的博文、賽事結(jié)果等。
在客戶端獲取服務(wù)器發(fā)送的數(shù)據(jù)并更新
<!DOCTYPE html> <html> <body> <h1>獲得服務(wù)器更新</h1> <div id="result"> </div> <script>if(typeof(EventSource)!=="undefined"){ var source=new EventSource("http://www.w3school.com.cn/example/html5/demo_sse.php"); source.onmessage=function(event) { document.getElementById("result").innerHTML+=event.data + "<br />"; }; }else{ document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";} </script> </body> </html>
配套的服務(wù)端代碼(PHP或ASP)如下:
<?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $time = date('r'); echo "data: The server time is: {$time}\n\n"; flush(); ?>
代碼解釋:
把報頭 “Content-Type” 設(shè)置為 “text/event-stream”
規(guī)定不對頁面進行緩存
輸出發(fā)送日期(始終以 “data: ” 開頭)
向網(wǎng)頁刷新輸出數(shù)據(jù)?
檢測 Server-Sent 事件支持
以下實例,我們編寫了一段額外的代碼來檢測服務(wù)器發(fā)送事件的瀏覽器支持情況:
if(typeof(EventSource)!=="undefined") { // 瀏覽器支持 Server-Sent // 一些代碼..... } else { // 瀏覽器不支持 Server-Sent.. }
服務(wù)器端代碼實例
為了讓上面的例子可以運行,您還需要能夠發(fā)送數(shù)據(jù)更新的服務(wù)器(比如 PHP 和 ASP)。
服務(wù)器端事件流的語法是非常簡單的。把 "Content-Type" 報頭設(shè)置為 "text/event-stream"?,F(xiàn)在,您可以開始發(fā)送事件流了。
實例
<?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $time = date('r'); echo "data: The server time is: {$time}\n\n";flush(); ?> ASP 代碼 (VB) (demo_sse.asp): <% Response.ContentType="text/event-stream" Response.Expires=-1 Response.Write("data: " & now()) Response.Flush() %>
代碼解釋:
把報頭 "Content-Type" 設(shè)置為 "text/event-stream"
規(guī)定不對頁面進行緩存
輸出發(fā)送日期(始終以 "data: " 開頭)
向網(wǎng)頁刷新輸出數(shù)據(jù)
EventSource 對象
在上面的例子中,我們使用 onmessage 事件來獲取消息。不過還可以使用其他事件:
事件 ? ? ? ? ? ? ? ? ? ? ? ? ? ? 描述
onopen ? ? ? ? ? 當(dāng)通往服務(wù)器的連接被打開 ? ?
onmessage ? ? 當(dāng)接收到消息 ? ?
onerror ? ? ? ? ? ?當(dāng)發(fā)生錯誤 ? ?