自己的开发路

HTML5 服务器发送事件(Server-Sent Events

2018-07-04  本文已影响16人  冰镇苏打水

HTML5 服务器发送事件(Server-Sent Events)

Server-Sent 事件 - 单向消息传递

Server-Sent 事件指的是网页自动获取来自服务器的更新。

曾经写过Web端展示二维码,手机扫描.更新数据库.Web 端页面等待数据库更新就是用 setInterval(code, milliseconds)调用 AJAX 查询数据库

还有一个大盘展示系统,用来展示公司的数据更新.也是用上面的方法,特别 low.

当然,更 low 的也就是window.location.reload();

偶然发现 HTML5 有这样的 API

接收 Server-Sent 事件通知

web端

可以打印一下接受到什么参数

<script>
    var source = new EventSource("http://localhost/te_inner_web/login/server_post.json");

//    处理连接报错
    source.onerror = function (e) {
        console.log(e);
    };

//    初次连接提示
    source.onopen = function () {
        console.log("连接打开...");
    };

//    收到消息,处理事件
    source.onmessage = function (event) {
        console.log(event);
        document.querySelector("body").innerHTML += event.data + "<br>";

//        收到一次就关闭连接,如果注释掉,则持续连接
        source.close();
    };
</script>
服务端
public function serverPost()
{
     // 把报头 "Content-Type" 设置为 "text/event-stream"
    header('Content-Type: text/event-stream');
    // 规定不对页面进行缓存
    header('Cache-Control: no-cache');


    $date = date('Y-m-d H:i:s');
    // 输出信息 (始终以 "data: " 开头)
    echo "data: {$date}\n\n";
    // 向网页刷新输出数据
    flush();
}

注:放弃 IE 吧

上一篇下一篇

猜你喜欢

热点阅读