這篇文章主要介紹html5之sse服務(wù)器發(fā)送事件EventSource的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
五蓮網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)公司!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)公司等網(wǎng)站項目制作,到程序開發(fā),運營維護。創(chuàng)新互聯(lián)公司從2013年開始到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)公司。
Server-Sent Events使用
Server-Sent Events使用很簡單,通過EventSource 對象來接受服務(wù)器端消息。有如下事件:
onopen 當通往服務(wù)器的連接被打開
onmessage 當接收到消息
onerror 當發(fā)生錯誤
檢測 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ù)器端代碼實例
<?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."); }; } else { document.getElementById("result").innerHTML="抱歉,你的瀏覽器不支持 server-sent 事件..."; }
我們會發(fā)現(xiàn),控制臺打印如下:
不停的進入鏈接、和錯誤,詳情請點擊
那是因為php代碼只是簡單的echo,并沒有連續(xù)輸出,我們把上面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); } ?>
就不會出現(xiàn)不停錯誤了!
IE瀏覽器兼容解決方案
我們知道,IE瀏覽器并不支持EventSource,有如下解決方案:
引入
eventsource.min.js
就可以完美解決。可以查看其github地址:https://github.com/Yaffle/EventSource 結(jié)合nodejs使用也很方便,直接
npm install event-source-polyfill
以上是“html5之sse服務(wù)器發(fā)送事件EventSource的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
標題名稱:html5之sse服務(wù)器發(fā)送事件EventSource的示例分析
分享地址:http://www.chinadenli.net/article48/jsgdep.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、App開發(fā)、云服務(wù)器、搜索引擎優(yōu)化、外貿(mào)網(wǎng)站建設(shè)、虛擬主機
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)