Vue3连接mqtt订阅消息

Vue3 中使用以及订阅

没有安装可使用 npm install mqtt --save (暂时使用了npm install mqtt@3.0.0

页面引入

引用mqtt库 不要直接引用mqtt 会报错
import mqtt from 'mqtt/dist/mqtt'

代码:

1.获取动态配置(关于mqtt的动态配置)

<script>
// //引入mqtt
import mqtt from "mqtt/dist/mqtt";
export default {
 data() {
    return {
      client: {},
    };
  },
  created() {
    this.getrtm_index_config(); //获取运行配置获取并建立mqtt
  },
  methods: {
    //运行配置获取并建立mqtt
    getrtm_index_config() {
      const rtm_index_config_url = "/api/kui/rtm_index_config?token=" + token;
      this.$myaxios.get(rtm_index_config_url).then((res) => {
        this.rtmindexconfig = res.data;
        this.mqttconnect(this.rtmindexconfig.mqtt);
      });
    },
  },
}
</script>

2.建立mqtt

    mqttconnect(_config) {
      var _port = _config.connection.port;
      var _path = "/ws";
      var _usessl = false;
      if (location.protocol == "https:") {
        _port = _config.connection.porthttps;
        _path = "/ws";
        _usessl = true;
      }
      var _hostname = _config.connection.hostname;
      if (_hostname == "") {
        //什么也都没有配置,那么按浏览器的来
        _hostname = location.hostname;
        var tport = location.port;
        if (tport == "") {
          if (_usessl) {
            tport = "443";
          } else {
            tport = "80";
          }
        }
        _port = parseInt(tport);
      }
      const options = {
        connectTimeout: 4000,
        clean: true, // 保留会话
        connectTimeout: 4000, // 超时时间
        reconnectPeriod: 4000, // 重连时间间
        clientId: "emqx_vue_" + Math.random().toString(16).substring(2, 8), //唯一值
        port: _config.connection.port, //端口  port  9000
        host: _hostname, //地址
        username: _config.connection.username, //id
        password: _config.connection.password,
      };
      var controlWsUrl = `ws://${options.host}:${options.port}/ws`;
      console.error(controlWsUrl);
      //创建实例 传入地址和参数对象
      this.client = mqtt.connect(controlWsUrl, options);
      this.client.on("reconnect", (error) => {
        console.log("正在重连:", error);
      });
      //连接成功
      this.client.on("connect", (e) => {
        //订阅主题
        this.onConnect(_config);
        //监听接收信息
        this.getmqMessage();
      });
    },

mqtt地址例如:

3.订阅主题

    //订阅主题
    onConnect(_config) {
      console.error(_config.config.topic);
      var spichar = "/";
      var t = _config.config.topic + spichar + "all" + spichar + "#"; //匹配 iopmsglist/all iopmsglist/all/xxx
      this.client.subscribe(t, 0, (error, res) => {
        if (error) {
          console.log("订阅主题错误", error);
          return;
        }
        console.log("订阅主题", res);
      });
    },

4.监听接收信息

   //监听接收消息
    getmqMessage() {
      this.client.on("message", (topic, message) => {
        if (message) {
          console.error("收到来着", topic, "的信息", message.toString());
        }
      });
    },

 收到的信息需要toString,否则默认他是Uint8Array格式

 

posted @ 2024-04-02 16:25  じ逐梦  阅读(691)  评论(0编辑  收藏  举报