前端使用sse长连接单向通信

后端使用nodejs+express框架

const express = require('express'); //引用框架
const app = express(); //创建服务
const port = 8088; //项目启动端口

//设置跨域访问
app.all("*", function(req:any, res:any, next:any) {
 //设置允许跨域的域名,*代表允许任意域名跨域
 res.header("Access-Control-Allow-Origin", '*');
 //允许的header类型
 res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
 //跨域允许的请求方式 
 res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
 // 可以带cookies
 res.header("Access-Control-Allow-Credentials", true);
 if (req.method == 'OPTIONS') {
  res.sendStatus(200);
 } else {
  next();
 }
})

app.get("/sse",(req:any,res:any) => {
    res.set({
        'Content-Type': 'text/event-stream', //设定数据类型
        'Cache-Control': 'no-cache',// 长链接拒绝缓存
        'Connection': 'keep-alive' //设置长链接
      });

      console.log("进入到长连接了")
      //持续返回数据
      setInterval(() => {
        console.log("正在持续返回数据中ing")
        const data = {
          message: `Current time is ${new Date().toLocaleTimeString()}`
        };
        res.write(`data: ${JSON.stringify(data)}\n\n`);
      }, 1000);  
})

//创建项目
app.listen(port, () => {
 console.log(`项目启动成功-http://localhost:${port}`)
}) 

前端随便一个HTML都行

        const source = new EventSource('http://localhost:8088/sse/')
        //对于建立链接的监听
        source.onopen = function (event) {
            console.log(source.readyState);
            console.log("长连接打开");
        };

        //对服务端消息的监听
        source.onmessage = function (event) {
            console.log(JSON.parse(event.data));
            console.log("收到长连接信息");
        };

        //对断开链接的监听
        source.onerror = function (event) {
            console.log(source.readyState);
            console.log("长连接中断");
        };
  1. SSE比websocket更轻

  2. SSE是基于http/https协议的

  3. 如果只需要服务端向客户端推送消息,推荐使用SSE

  4. IE及小程序不支持SSE

  5. SSE默认支持断线重连

  6. SSE支持自定义发送的数据类型

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值