- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > web開(kāi)發(fā) >
- html5之sse服務(wù)器發(fā)送事件EventSource的示例分析
這篇文章主要介紹html5之sse發(fā)送事件EventSource的示例分析,文中介紹的非常詳細,具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
Server-Sent Events使用
Server-Sent Events使用很簡(jiǎn)單,通過(guò)EventSource 對象來(lái)接受服務(wù)器端消息。有如下事件:
onopen 當通往服務(wù)器的連接被打開(kāi)
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ù)器端代碼實(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(); ?>
鏈接事件和報錯事件都加上
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ā)現,控制臺打印如下:
不停的進(jìn)入鏈接、和錯誤,詳情請點(diǎn)擊
那是因為php代碼只是簡(jiǎn)單的echo,并沒(méi)有連續輸出,我們把上面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ì )出現不停錯誤了!
IE瀏覽器兼容解決方案
我們知道,IE瀏覽器并不支持EventSource,有如下解決方案:
引入
eventsource.min.js
就可以完美解決??梢圆榭雌鋑ithub地址:https://github.com/Yaffle/EventSource 結合nodejs使用也很方便,直接
npm install event-source-polyfill
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系站長(cháng)郵箱:ts@56dr.com進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2 建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站