前言
我前面文章講過數據大屏,里面的數據時時更新。還有時時更新的股票數據,Facebook/Twitter 更新、估價更新、新的博文、賽事結果等等,都需要數據時時更新。之前我們一般都是請求服務器,看看有沒有可以更新的數據。html5提供了Server-Sent Events方法,通過服務器發送事件,更新能夠自動到達。
Server-Sent Events使用
Server-Sent Events使用很簡單,通過EventSource 對象來接受服務器端消息。有如下事件:
onopen 當通往服務器的連接被打開
onmessage 當接收到消息
onerror 當發生錯誤
檢測 Server-Sent 事件支持
if(typeof(EventSource)!== undefined ) // 瀏覽器支持 Server-Sent // 一些代碼.....// 瀏覽器不支持 Server-Sent..}
接收 Server-Sent 事件通知
var source=new EventSource( haorooms_sse.php source.onmessage=function(event) document.getElementById( result ).innerHTML+=event.data + br };
服務器端代碼實例
?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(); ? 鏈接事件和報錯事件都加上
if(typeof(EventSource)!== undefined ) var source=new EventSource( server.php source.onopen=function() console.log( Connection to server opened. source.onmessage=function(event) document.getElementById( result ).innerHTML+=event.data + br source.onerror=function() console.log( EventSource failed. document.getElementById( result ).innerHTML= 抱歉,你的瀏覽器不支持 server-sent 事件... }
我們會發現,控制臺打印如下:

不停的進入鏈接、和錯誤,詳情請點擊
那是因為php代碼只是簡單的echo,并沒有連續輸出,我們把上面php代碼做如下改進
?php header( Content-Type: text/event-stream header( Cache-Control: no-cache $time = date( r $i = 0; $c = $i + 100; while (++$i $c) { echo id: . $i . /n echo data: . $time. /n/n ob_flush(); flush(); sleep(1);? 就不會出現不停錯誤了!
IE瀏覽器兼容解決方案
我們知道,IE瀏覽器并不支持EventSource,有如下解決方案:
引入
eventsource.min.js
就可以完美解決。可以查看其github地址:https://github.com/Yaffle/EventSource 結合nodejs使用也很方便,直接
npm install event-source-polyfill
就可以了。
以上就是html5中sse服務器發送事件EventSource相關介紹的詳細內容,html教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答