Server-Sent Events 服务端单向客户端

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <h4>SSE</h4>

  <button id="btn">建立连接</button>
  <button id="close">关闭连接</button>
  <script>

    let source = null;


    // 连接
    document.querySelector('#btn').onclick = function () {

      source = new EventSource('http://192.168.10.164:8844/stream');

      source.addEventListener('open', function (event) {
        console.log('连接:ok');
      }, false);

      source.addEventListener('message', function (event) {
        var message = event.data;
        console.log('message:' + message);
      }, false);

    };

    // 关闭
    document.querySelector('#close').onclick = function () {
      source.close();
    };


  </script>

</body>

</html>

node服务端
 

var http = require("http");
var fs = require("fs");

http.createServer(function (req, res) {

  // 获取html
  if (req.url == '/index') {
    fs.readFile(__dirname + "/index.html", (err, data) => {
      if (err) {
        return console.log(err.message);
      }
      res.end(data);
    });
  }

  // 建立连接
  if (req.url === "/stream") {
    res.writeHead(200, {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      "Connection": "keep-alive",
      "Access-Control-Allow-Origin": '*',
    });
    res.write("retry: 10000\n"); // 浏览器重新发送间隔时间(断连时)
    res.write("event: connecttime\n"); // 自定义的事件类型,默认是message事件(浏览器监听)
    res.write(`id: ${Math.random()}\n`); // 浏览器用lastEventId属性读取这个值。一旦断线,浏览器发送一个HTTP头,里面包含一个特殊的Last-Event-ID头信息,将这个值发送回来,用来帮助服务器端重建连接
    res.write("data: 测试1 \n\n"); 
    res.write("data: 测试2 \n\n"); // 发送的数据

    interval = setInterval(function () {
      res.write("data: " + (new Date()) + "\n\n"); 
    }, 1000);

    req.addListener("close", function () {
      clearInterval(interval);
    }, false);


  }

}).listen(8844);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值