Mqtt封装

import Stomp from "stompjs";

import { ElMessage } from "element-plus";

import globalEvent from "@/utils/globalEvent";

class Socket {

  // socket 对象

  client;

  config;

  constructor(config) {

    this.config = config;

    // this.init();

  }

  numberOfRetries = 0;

  // 启动socket

  init() {

    const config = this.config;

    this.client = Stomp.client(this.config.socket.MQTT_SERVICE);

    //初始化mqtt客户端,并连接mqtt服务

    const headers = {

      login: this.config.socket.MQTT_USERNAME,

      passcode: this.config.socket.MQTT_PASSWORD,

    };

    this.client.connect(

      headers,

      function () {debugger

        const topic = config.socket.topic;

        this.subscribe(

          topic,

          (frame) => {debugger

            globalEvent.$emit("rmqGetActionMenu", frame.body);

          },

          (frame) => console.log("socket 订阅失败 ", frame)

        );

      },

      (frame) => {debugger

        console.error("socket 连接失败 ", frame);

        if (this.numberOfRetries % 5 === 0)

          ElMessage.warning("网络不稳定,请稍后");

        if (this.numberOfRetries === 0) {

          this.numberOfRetries++;

          this.init();

        } else {

          setTimeout(() => {

            this.numberOfRetries++;

            this.init();

          }, 3000);

        }

      }

    );

  }

}

export default Socket;


版权声明:本文为weixin_42499566原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。