html5 服务端推送

2017-01-11 15:23:45来源:segmentfault作者:小脑fu人点击

html部分


<!DOCTYPE html>
<html>
<body>
<h1>获得服务器更新</h1>
<button id='close'>断开sse</button>
<div></div><script>
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource("http://localhost:8000/events");
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br />";
};
}
else
{
document.getElementById("result").innerHTML="抱歉,您的浏览器不支持 server-sent 事件 ...";
}
var closeBtn=document.getElementById('close');
closeBtn.onclick=closeSSE;
function closeSSE(){
source.close();
document.getElementById("result").innerHTML+='断开sse链接' + "<br />";
}
</script></body>
</html>

服务器端部分,nodejs为例


var http = require('http');
// var sys = require('sys');
var fs = require('fs');http.createServer(function(req, res) {
// debugHeaders(req);if (req.headers.accept && req.headers.accept == 'text/event-stream') {
if (req.url == '/events') {
sendSSE(req, res);
} else {
res.writeHead(404);
res.end();
}
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
// res.write(fs.readFileSync(__dirname + '/sse-node.html'));
res.write(fs.readFileSync(__dirname + '/sse.html'));
res.end();
}
}).listen(8000);
function sendSSE(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});var id = (new Date()).toLocaleTimeString();setInterval(function() {
constructSSE(res, id, (new Date()).toLocaleTimeString());
}, 5000);constructSSE(res, id, (new Date()).toLocaleTimeString());
//res.end();
}
function constructSSE(res, id, data) {
res.write('id: ' + id + '/n');
res.write("data: " + data + '/n/n');
}// function debugHeaders(req) {
// sys.puts('URL: ' + req.url);
// for (var key in req.headers) {
// sys.puts(key + ': ' + req.headers[key]);
// }
// sys.puts('/n/n');
// }

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台