websocket连接

https://blog.csdn.net/qq_70071513/article/details/133171580

//暴露自定义websocket对象
export const socket = {
  //后台请求路径
  url: "",
  //websocket对象
  websocket: null,
  //websocket状态
  websocketState: false,
  //重新连接次数
  reconnectNum: 0,
  //重连锁状态,保证重连按顺序执行
  lockReconnect: false,
  //定时器信息
  timeout: null,
  clientTimeout: null,
  serverTimeout: null,
  //初始化方法,根据url创建websocket对象封装基本连接方法,并重置心跳检测
  initWebSocket(newUrl) {
    socket.url = newUrl;
    socket.websocket = new WebSocket(socket.url);
    socket.websocket.onopen = socket.websocketOnOpen;
    socket.websocket.onerror = socket.websocketOnError;
    socket.websocket.onclose = socket.websocketOnClose;
    this.resetHeartbeat()
  },
  reconnect() {
    //判断连接状态
    if (socket.lockReconnect) return;
    socket.reconnectNum += 1;
    //重新连接三次还未成功调用连接关闭方法
    if (socket.reconnectNum === 3) {
      socket.reconnectNum = 0;
      socket.websocket.onclose()
      return;
    }
    //等待本次重连完成后再进行下一次
    socket.lockReconnect = true;
    //5s后进行重新连接
    socket.timeout = setTimeout(() => {
      socket.initWebSocket(socket.url);
      socket.lockReconnect = false;
    }, 5000);
  },
  //重置心跳检测
  resetHeartbeat() {
    socket.heartbeat();
  },
  //心跳检测
  heartbeat() {
    socket.clientTimeout = setTimeout(() => {
      if (socket.websocket) {
        //向后台发送消息进行心跳检测
        socket.websocket.send(JSON.stringify({ type: "heartbeat" }));
        socket.websocketState = false;
        //一分钟内服务器不响应则关闭连接
        socket.serverTimeout = setTimeout(() => {
          if (!socket.websocketState) {
            socket.websocket.onclose()
          } else {
            this.resetHeartbeat()
          }
        }, 60 * 1000);
      }
    }, 3 * 1000);
  },
  //发送消息
  sendMsg(message) {
    socket.websocket.send(JSON.stringify({ type: "message", message: message}));
  },
  websocketOnOpen(event) {
    //连接开启后向后台发送消息进行一次心跳检测
    socket.websocket.send(JSON.stringify({ type: "heartbeat" }));
  },
  websocketOnError(error) {
    console.log(error);
    socket.reconnect();
  },
  websocketOnClose() {
    socket.websocket.close();
  },
};

 

 

2.引入websocket.js

//引入socket对象
import { socket } from "@/utils/websocket";

 

3.使用

created() {
    this.getMessageNumber()
    //初始化websocket对象
    socket.initWebSocket(process.env.VUE_APP_BASE_WS + "/" + window.localStorage.getItem("webSocketKey"));
    //绑定接收消息方法
    socket.websocket.onmessage = this.websocketOnMessage;
  },
  beforeDestroy() {
    // 组件销毁时关闭链接释放资源
    socket.websocketOnClose()
  },
  methods: {
    /** 初始化连接测试*/
    init() {
      socket.websocketOnOpen();
    },

    /** 接收websocket消息*/
    websocketOnMessage(event) {
      //初始化界面时,会主动向后台发送一次消息,获取数据
      this.websocketCount += 1;

      //没有发送成功则重新初始化一次
      if (this.websocketCount === 0) {
        this.init();
      }
      let info = JSON.parse(event.data);
      switch (info.type) {
        case "heartbeat":
          socket.websocketState = true;
          break;
        case "message":
          this.loading = true;
          this.$nextTick(() => {
            // 收到文本消息
            this.consumeTextMessage(info)
            
            //收到文件消息
            //this.consumeFileMessage(info);
          })
          break;
        case "error":
          this.loading = false;
          break;
      }
    },

    /** 处理推送的文本数据 */
    consumeTextMessage(info) {
      const h = this.$createElement;
      this.$notify({
        title: '新的通知',
        message: h('i', { style: 'color: teal'}, info.message)
      });
    },

    /** 处理推送的文件数据 这里发送的是xlsx文件,可根据需求自定义,也可以将文件名一起从后端传过来 */
    consumeFileMessage(info) {
      let infoObj = info
      //服务器向客户端推送文件  生成文件
      Base64StrToFileUtil.downloadFileByBase64(infoObj.message, "01.xlsx")
    }
  }

  

 

posted @ 2024-08-15 18:12  南瓜壳  阅读(13)  评论(0编辑  收藏  举报