• 技术文章 >web前端 >html教程

    html5中sse服务器发送事件EventSource相关介绍

    巴扎黑巴扎黑2017-09-02 10:00:03原创1476
    本篇文章主要介绍了浅谈html5之sse服务器发送事件EventSource介绍,具有一定的参考价值,有兴趣的可以了解一下

    前言

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

    Server-Sent Events使用

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

    检测 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

    就可以了。

    以上就是html5中sse服务器发送事件EventSource相关介绍的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:EventSource html5 服务器
    上一篇:HTML制作网页动态时钟教程 下一篇:html5+CSS3+JS七夕告白功能实现详解
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【活动】充值PHP中文网VIP即送云服务器• 新手的成长记录点滴(十)_html/css_WEB-ITnose• tomcat 服务器全解_html/css_WEB-ITnose• 对于DIV+CSS的开发方式,我们也要听听另外的声音.(转贴)_html/css_WEB-ITnose• 面向对象_基于原型链实现继承• 如何获得个人项目的前 1000 个受众?_html/css_WEB-ITnose
    1/1

    PHP中文网