前言
本文主要通过实现1个客户端时钟效果(不受客户端时间影响),来主要捋捋server-sent events技术。
HTML5主要有这么几个模块:(文档可以看这里)
- 语义
- 通信
- 离线 & 存储
- 3D绘图 & 效果
- 性能 & 集成
- 设备访问
- 样式
其中,通信模块中,有这么几个新技术,分别是 webSocket(全双工通信)、Server-sent events(服务器推送) 和 webRTC(网页即时通信)
Server-sent events 应用场景
应用场景我能想到的有,实时展示类的,像客户端时钟,比如活动页面信息推送(如中奖人员、蚂蚁森林活动时实时浇水人等(蚂蚁森林这个不一定是server-sent events实现的,只是说可以这样实现))
展示效果(实时变动,此处只是截图)
客户端API
主要用到的是 EventSource实例 (初始化时传入url即可创建连接,可跨域,支持断线自动重连),它主要有以下几个方法和属性(IE不支持,我用的是IE Edge)
1、onopen 方法,监听连接成功事件
2、onmessage 方法,监听接收到消息事件
3、onerror 方法,监听出错事件(比如运行过程中,后端代码挂了,连接出错等等)
4、close 方法,关闭连接
5、readyState 属性,值分别是 0 , 1 , 2(未连接或重新连接,已连接,已断开)
客户端实现代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>server sent events</title>
</head>
<body>
<button id="start">点击连接</button>
<button id="stop">点击结束</button>
<div id="example"></div>
<script>
var source = null;
var startBtn = document.getElementById('start');
startBtn.onclick = function(){
if(source !== null){
return ;
}
source = new EventSource('http://127.0.0.1:8844/stream');
var div = document.getElementById('example');
source.onopen = function(event){
// console.log('onopen,=============');
// console.log(event)
}
var message;
source.onmessage = function(event){
// console.log('onmessage=======')
// console.log(event);
// 时间戳转日期时间
message = timeStamp2date('Y-m-d H:i:s',(event.data/1000));
div.innerHTML = `<p>当前时间为: ${message}</p>`
}
source.onerror = function(error){
console.log('onerror==============');
console.log(error);
}
}
var stopBtn = document.getElementById('stop');
stopBtn.onclick = function(){
if(source === null){
alert('not open');
}else{
source.close();
source = null;
}
}
/**
* 时间戳格式化函数
* @param {string} format 格式
* @param {int} timestamp 要格式化的时间 默认为当前时间
* @return {string} 格式化的时间字符串
*/
function timeStamp2date(format, timestamp){
var a, jsdate=((timestamp) ? new Date(timestamp*1000) : new Date());
var pad = function(n, c){
if((n = n + "").length < c){
return new Array(++c - n.length).join("0") + n;
} else {
return n;
}
};
var txt_weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var txt_ordin = {1:"st", 2:"nd", 3:"rd", 21:"st", 22:"nd", 23:"rd", 31:"st"};
var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var f = {
// Day
d: function(){return pad(f.j(), 2)},
D: function(){return f.l().substr(0,3)},
j: function(){return jsdate.getDate()},
l: function(){return txt_weekdays[f.w()]},
N: function(){return f.w() + 1},
S: function(){return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th'},
w: function(){return jsdate.getDay()},
z: function(){return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0},
// Week
W: function(){
var a = f.z(), b = 364 + f.L() - a;
var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
return 1;
} else{
if(a <= 2 && nd >= 4 && a >= (6 - nd)){
nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
return date("W", Math.round(nd2.getTime()/1000));
} else{
return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
}
}
},
// Month
F: function(){return txt_months[f.n()]},
m: function(){return pad(f.n(), 2)},
M: function(){return f.F().substr(0,3)},
n: function(){return jsdate.getMonth() + 1},
t: function(){
var n;
if( (n = jsdate.getMonth() + 1) == 2 ){
return 28 + f.L();
} else{
if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
return 31;
} else{
return 30;
}
}
},
// Year
L: function(){var y = f.Y();return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0},
//o not supported yet
Y: function(){return jsdate.getFullYear()},
y: function(){return (jsdate.getFullYear() + "").slice(2)},
// Time
a: function(){return jsdate.getHours() > 11 ? "pm" : "am"},
A: function(){return f.a().toUpperCase()},
B: function(){
// peter paul koch:
var off = (jsdate.getTimezoneOffset() + 60)*60;
var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off;
var beat = Math.floor(theSeconds/86.4);
if (beat > 1000) beat -= 1000;
if (beat < 0) beat += 1000;
if ((String(beat)).length == 1) beat = "00"+beat;
if ((String(beat)).length == 2) beat = "0"+beat;
return beat;
},
g: function(){return jsdate.getHours() % 12 || 12},
G: function(){return jsdate.getHours()},
h: function(){return pad(f.g(), 2)},
H: function(){return pad(jsdate.getHours(), 2)},
i: function(){return pad(jsdate.getMinutes(), 2)},
s: function(){return pad(jsdate.getSeconds(), 2)},
//u not supported yet
// Timezone
//e not supported yet
//I not supported yet
O: function(){
var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
return t;
},
P: function(){var O = f.O();return (O.substr(0, 3) + ":" + O.substr(3, 2))},
//T not supported yet
//Z not supported yet
// Full Date/Time
c: function(){return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P()},
//r not supported yet
U: function(){return Math.round(jsdate.getTime()/1000)}
};
return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
if( t!=s ){
// escaped
ret = s;
} else if( f[s] ){
// a date function exists
ret = f[s]();
} else{
// nothing special
ret = s;
}
return ret;
});
}
</script>
</body>
</html>
服务端代码可看这里:(Node.js代码,懒得自己写了,来自阮一峰博客)
var http = require("http");
http.createServer(function (req, res) {
var fileName = "." + req.url;
if (fileName === "./stream") {
res.writeHead(200, {
"Content-Type":"text/event-stream",
"Cache-Control":"no-cache",
"Connection":"keep-alive",
"Access-Control-Allow-Origin": '*',
});
console.log('有人连接进来了...')
res.write("retry: 10000\n");
res.write("event: connecttime\n");
// res.write("data: " + (new Date()) + "\n\n");
// res.write("data: " + (new Date()) + "\n\n");
interval = setInterval(function () {
res.write("data:" + (new Date()).getTime()+ "\n\n");
}, 1000);
req.connection.addListener("close", function () {
clearInterval(interval);
}, false);
}
}).listen(8844, "127.0.0.1");
原理
服务器是以流的形式给客户端推送数据,具体的我也不懂,就不bb了。