国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

html5之sse服務(wù)器發(fā)送事件EventSource的示例分析

發(fā)布時(shí)間:2021-07-27 11:48 來(lái)源:億速云 閱讀:0 作者:小新 欄目: web開(kāi)發(fā)

這篇文章主要介紹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í),將立刻刪除涉嫌侵權內容。

AV片在线观看| 亚洲欧美中文日韩在线v日本| 亚洲VA在线VA天堂VA欧美VA| 国产伦精品一区二区三区免费| 成人无码特黄特黄AV片在线| 久久精品国产一区二区三区|