浅谈html5之sse服务器发送事件EventSource介绍

发布时间:2022-04-13 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了浅谈html5之sse服务器发送事件EventSource介绍脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

前言

我前面文章讲过数据大屏,里面的数据时时更新。还有时时更新的股票数据,FaceBook/TwITter 更新、估价更新、新的博文、赛事结果等等,都需要数据时时更新。之前我们一般都是请求服务器,看看有没有可以更新的数据。htML5提供了Server-sent Events方法,通过服务器发送事件,更新能够自动到达。

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

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

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

那是因为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

就可以了。

github地址:https://github.com/confidence68/demoOfSocket/tree/master/serversent

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本宝典。

脚本宝典总结

以上是脚本宝典为你收集整理的浅谈html5之sse服务器发送事件EventSource介绍全部内容,希望文章能够帮你解决浅谈html5之sse服务器发送事件EventSource介绍所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:html5html5