HTML5 SSE -- Server Sent Events 服务器推送事件
EventSource 对象的使用
<script>
if (typeof (EventSource) !== "undefined") {
var source = new EventSource("xxx.php");
source.onmessage = function (event) {
console.log(event);
};
source.onerror = function (event) {
console.log("error"+event);
}
source.onopen = function () {
console.log('open');
}
}
</script>
服务端代码
下面是最简单的服务端代码了,默认推送的事件流就是 message 类型的(也可以自定义事件流的类型)
<?php
header('Content-type: text/event-stream');//必须的
//header('Cache-control: no-cache');
$time = time();
//echo "event: update\n";//事件流类型 \n结束
echo "data: {$time}\n\n";//\n\n结束 结尾符号不能省略
flush();
更具体的栗子
当然实际的项目中你不太可能会这样做。但是却能很好的加深你对 SSE的理解。
前端html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SSE</title>
</head>
<body>
<button onclick="dotest1();">测试按钮1</button>
<button onclick="dotest2();">测试按钮2</button>
</body>
<script>
//测试代码
var evtSource;
function dotest1() {
evtSource && evtSource.close();
evtSource = new EventSource('sse.php?act=edit');
evtSource.addEventListener('update' ,function(e){
console.log('update !'+e.data)
});
}
function dotest2() {
evtSource && evtSource.close();
evtSource = new EventSource('sse.php?act=del');
evtSource.addEventListener('delete' ,function(e){
console.log('delete !'+e.data)
});
}
</script>
</html>
服务端sse.php
<?php
header('Content-type: text/event-stream');
header('Cache-control: no-cache');
$act = $_GET['act'];
$now = time();
switch ($act) {
case 'edit':
echo "event: update\n";
echo "id: 111\n";
break;
case 'del':
echo "event: delete\n";
echo "id: 222\n";
break;
}
echo "data: {$now}\n\n";
//echo "retry: 5000";//重连时间
flush();
说明
前端就2个按钮
- 按钮1 点击后 创建EventSource 对象,并监听 update 事件
- 按钮2 点击后 同样创建EventSource 对象,并监听 delete 事件
打开谷歌浏览器的控制台你能看到一些相关的信息。默认的推送时间是3秒。