淺談html5之sse服務(wù)器發(fā)送事件EventSource介紹

前言
我前面文章講過數(shù)據(jù)大屏,里面的數(shù)據(jù)時(shí)時(shí)更新。還有時(shí)時(shí)更新的股票數(shù)據(jù),F(xiàn)acebook/Twitter 更新、估價(jià)更新、新的博文、賽事結(jié)果等等,都需要數(shù)據(jù)時(shí)時(shí)更新。之前我們一般都是請求服務(wù)器,看看有沒有可以更新的數(shù)據(jù)。html5提供了Server-Sent Events方法,通過服務(wù)器發(fā)送事件,更新能夠自動(dòng)到達(dá)。
Server-Sent Events使用
Server-Sent Events使用很簡單,通過EventSource 對象來接受服務(wù)器端消息。有如下事件:
- onopen 當(dāng)通往服務(wù)器的連接被打開
- onmessage 當(dāng)接收到消息
- onerror 當(dāng)發(fā)生錯(cuò)誤
檢測 Server-Sent 事件支持
if(typeof(EventSource)!=="undefined") { // 瀏覽器支持 Server-Sent // 一些代碼..... } else { // 瀏覽器不支持 Server-Sent.. }
接收 Server-Sent 事件通知
var source=new EventSource("haorooms_sse.php"); source.onmessage=function(event) { document.getElementById("result").innerHTML+=event.data + "<br>"; };
服務(wù)器端代碼實(shí)例
<?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(); ?>
鏈接事件和報(bào)錯(cuò)事件都加上
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."); }; } else { document.getElementById("result").innerHTML="抱歉,你的瀏覽器不支持 server-sent 事件..."; }
我們會(huì)發(fā)現(xiàn),控制臺(tái)打印如下:
不停的進(jìn)入鏈接、和錯(cuò)誤,詳情請點(diǎn)擊
那是因?yàn)閜hp代碼只是簡單的echo,并沒有連續(xù)輸出,我們把上面php代碼做如下改進(jìn)
<?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); } ?>
就不會(huì)出現(xiàn)不停錯(cuò)誤了!
IE瀏覽器兼容解決方案
我們知道,IE瀏覽器并不支持EventSource,有如下解決方案:
引入
eventsource.min.js
就可以完美解決??梢圆榭雌鋑ithub地址:https://github.com/Yaffle/EventSource 結(jié)合nodejs使用也很方便,直接
npm install event-source-polyfill
就可以了。
github地址:https://github.com/confidence68/demoOfSocket/tree/master/serversent
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
HTML5 source標(biāo)簽:媒介元素定義媒介資源
HTML5 source標(biāo)簽是一種媒介元素(比如 <video> 和 <audio>)來定義媒介資源。接下來通過本文給大家介紹HTML5 source標(biāo)簽:媒介元素定義媒介資源的相關(guān)資料,2018-01-29