html5 服务端推送

html部分

<!DOCTYPE html>
<html>
<body>
<h1>获得服务器更新</h1>
<button id='close'>断开sse</button>
<div id="result"></div>

<script>
if(typeof(EventSource)!=="undefined")
  {
  //  支持跨域携带cookie
  var source=new EventSource("http://localhost:8000/events",{withCredentials: true});
  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();
}

//只有包含data:的数据行后面有空行时才触发message事件
//data:foo
//data:bar
//的event.data值为 "for/nbar" 注意换行符
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');
// }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值