温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

html5之sse服务器发送事件EventSource的示例分析

发布时间:2021-07-26 14:26:55 来源:亿速云 阅读:149 作者:小新 栏目:web开发

这篇文章主要介绍html5之sse服务器发送事件EventSource的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

Server-Sent Events使用

Server-Sent Events使用很简单,通过EventSource 对象来接受服务器端消息。有如下事件:

  • onopen 当通往服务器的连接被打开

  • onmessage 当接收到消息

  • onerror 当发生错误

检测 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>";
};

服务器端代码实例

<?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 事件...";
}

我们会发现,控制台打印如下:

html5之sse服务器发送事件EventSource的示例分析

不停的进入链接、和错误,详情请点击

那是因为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的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI