html5服务器发送事件(server-sent event)

HTML5服务器发送事件运行网页获取来自服务器的更新。

Server-Sent 事件 - 单向消息传递
Server-Sent 事件指的是网页自动获取来自服务器的更新。

浏览器支持
除了 Internet Explorer,所有主流浏览器均支持服务器发送事件。

EventSource
EventSource 对象用于接收服务器发送事件通知

事件 描述
onopen 当通往服务器的连接被打开时触发
onmessage 当接收到消息时触发
onerror 当错误发生时触发

示例:

前端页面代码

if(typeof(EventSource)!=="undefined"){//检测浏览器是否支持服务器发送事件
    var source=new EventSource("sse.php");//创建一个新的 EventSource 对象,然后规定发送更新的服务页面
    source.onmessage=function(event){//接受到消息时触发
        console.log(event.data);
    }
}else{
    console.log("抱歉,当前浏览器不支持server-sent事件!");
}

服务器端事件流的语法是非常简单的。把 “Content-Type” 报头设置为 “text/event-stream”就可以开始发送事件流了。

服务端页面(sse.php)代码

<?php
header('Content-Type: text/event-stream');//把报头 "Content-Type" 设置为 "text/event-stream"

header('Cache-Control: no-cache');//规定不对页面进行缓存

$time = date('r');//获取日期
echo "data: The server time is: {$time}\n\n";//输出发送信息,信息格式为:前缀"data:"+待传输的数据+"后缀\n\n"
flush();//向网页刷新输出数据
?>

参考网址:http://www.w3school.com.cn/html5/html_5_serversentevents.asp

猜你喜欢

转载自blog.csdn.net/yihanzhi/article/details/79802395
今日推荐