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关闭" + e.readyState);
  }
}
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()

你可能感兴趣的:(前端,vue)