sse实时通信

使用原因:用户网络环境较差,之前使用ws总是出现断连重连,导致数据总是不能实时更新,所以更换为sse

npm install event-source-polyfill

createWebSocket:创建sse连接 

getWebSocketMsg:接收sse消息

  import { EventSourcePolyfill } from "event-source-polyfill";
  import { getToken } from '@/utils/auth'
  class webSocketClass {
  constructor(name) {
    this.localUrl = `http`; //直连阿里云正式环境
    this.globalCallback = null;
    this.createWebSocket(name);
    this.readyState = 0;
  }
  createWebSocket(url) {
    var that =this
    // 建立连接
    this.eventSource = new EventSourcePolyfill(
      this.localUrl+ url,
      {
        // 设置重连时间
        heartbeatTimeout: 60 * 60 * 1000,
        // 添加token
        headers: {
          Authorization: `Bearer ${getToken()}`,
        },
      }
    );
    this.eventSource.onopen = (e) => {
      console.log("已建立SSE连接~");
    };
    this.eventSource.onmessage = (e) => {
      const d = JSON.parse(e.data);
      console.log("sse已接受到消息:", d);
      that.getWebSocketMsg(that.globalCallback);

    };
    this.eventSource.onerror = (e) => {
      console.log("SSE连接错误" + e.readyState);
      if (e.readyState == EventSource.CLOSED) {
        console.log("SSE连接关闭");
      } else if (this.eventSource.readyState == EventSource.CONNECTING) {
        console.log("SSE正在重连");
        //重新设置token
        this.eventSource.headers = {
          Authorization: `Bearer ${getToken()}`,
        };
      } else {
        console.log("error", e);
      }
    };
  }
  getWebSocketMsg(callback) {
      console.log("开始接收sse消息~",this.eventSource);
      this.eventSource.onmessage = (ev) => {
        callback && callback(ev);
    };
  }
  close(){
      this.eventSource.close()
      console.log("SSE关闭" );
  }
}
export default webSocketClass;

使用方法:

  this.warningSSE = new vueSSEUtil('/sse/warning/'+this.userId);
  this.warningSSE.getWebSocketMsg((evt) => {
      const d = JSON.parse(evt.data);
      d.warnCode = this.code_to_value(d.warnCode);
      console.log('sse回调数据',d) 
   });
     

一定要在页面退出关闭sse

this.warningSSE.close()

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SSE(Server-Sent Events)允许服务器向客户端发送事件流,这些事件可以是任意类型的数据,例如文本、JSON、XML 等等。客户端通过 EventSource 接口连接到服务器,服务器通过 HTTP 协议不断向客户端发送事件流,客户端可以实时处理这些事件。 在使用 SSE 进行实时输出时,服务器会不断地向客户端发送数据,客户端需要通过监听 onmessage 事件来实时处理接收到的数据。以下是一个简单的示例: ``` const eventSource = new EventSource('/stream'); // 连接到服务器的 SSE 接口 eventSource.onmessage = function(event) { const data = JSON.parse(event.data); // 解析接收到的数据 // 处理数据的代码 }; ``` 在服务器端,我们需要使用一些特殊的 HTTP 头部来启用 SSE。例如,下面是一个 Node.js 的示例: ``` const http = require('http'); http.createServer(function(request, response) { response.writeHead(200, { 'Content-Type': 'text/event-stream', // 指定响应内容的类型为 text/event-stream 'Cache-Control': 'no-cache', // 禁用缓存 'Connection': 'keep-alive' // 使用长连接保持连接 }); setInterval(function() { const data = JSON.stringify({ message: 'Hello, world!' }); response.write(`data: ${data}\n\n`); // 发送数据 }, 1000); }).listen(8080); ``` 在这个示例中,我们使用 setInterval 定时发送数据。在每次发送数据时,我们需要使用 data 字段来指定数据的内容,同时在数据后面添加两个换行符(\n\n)表示数据的结束。这是因为 SSE 的数据格式要求每个数据块以两个换行符(\n\n)结束。 以上就是使用 SSE 进行实时输出的基本流程。需要注意的是,SSE 只能用于服务器向客户端发送数据,客户端无法向服务器发送数据。如果需要双向通信,需要使用 WebSocket。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值