在 Vue中使用 MQTT 实现通信

一、安装 MQTT 客户端库

我们使用 mqtt.js,它是一个支持浏览器环境的 MQTT 客户端库。通过以下命令安装:

npm install mqtt

二、创建 MQTT 连接工具类

为了方便管理和复用 MQTT 客户端,我们创建一个工具类 mqttClient.js,放在 src/utils 目录下:

import mqtt from 'mqtt';

class MQTTClient {
  constructor(options) {
    this.client = null;
    this.messages = [];
    this.subscribers = {};
    this.defaultOptions = {
      clientId: 'vue-client_' + Math.random().toString(16).substr(2, 8),
      clean: true,
      connectTimeout: 4000,
      //username: '账号',
      //password: '密码'
    };
    this.options = { ...this.defaultOptions, ...options };
  }

  connect(brokerUrl) {
    return new Promise((resolve, reject) => {
      try {
        this.client = mqtt.connect(brokerUrl, this.options);

        this.client.on('connect', () => {
          console.log('连接成功');
          resolve(this.client);
        });

        this.client.on('error', (err) => {
          console.error('连接失败:', err);
          reject(err);
        });

        this.client.on('message', (topic, payload) => {
          const message = {
            topic: topic,
            content: payload.toString()
          };
          this.messages.push(message);
          
          // 如果有订阅者,通知所有订阅了该主题的回调
          if (this.subscribers[topic]) {
            this.subscribers[topic].forEach(callback => callback(message));
          }
        });

        this.client.on('close', () => {
          console.log('MQTT connection closed');
        });
      } catch (err) {
        reject(err);
      }
    });
  }
// 订阅主题
  subscribe(topic, callback, qos = 0) {
    if (!this.client || this.client.connected === false) {
      // console.error('MQTT not connected');
      return;
    }

    this.client.subscribe(topic, { qos }, (err) => {
      if (!err) {
        console.log(`Subscribed to ${topic}`);
        // 存储订阅回调
        if (!this.subscribers[topic]) {
          this.subscribers[topic] = [];
        }
        this.subscribers[topic].push(callback);
      }
    });
  }
// 取消订阅指定主题的方法
  unsubscribe(topic) {
    if (!this.client || this.client.connected === false) {
      console.error('MQTT not connected');
      return;
    }

    this.client.unsubscribe(topic, (err) => {
      if (!err) {
        console.log(`Unsubscribed from ${topic}`);
        // 移除订阅回调
        if (this.subscribers[topic]) {
          delete this.subscribers[topic];
        }
      }
    });
  }
// 发送消息
  publish(topic, message, qos = 0, retain = false) {
    if (!this.client || this.client.connected === false) {
      console.error('MQTT not connected');
      return;
    }

    this.client.publish(topic, message, { qos, retain }, (err) => {
      if (err) {
        console.error('Publish error:', err);
      }
    });
  }
// 取消连接
  disconnect() {
    if (this.client) {
      this.client.end();
      this.client = null;
    }
  }

  getMessages() {
    return [...this.messages];
  }

  clearMessages() {
    this.messages = [];
  }
}

export default MQTTClient;

三、在 Vue 组件中使用

我们创建一个 Vue 组件来使用 MQTT 客户端

<template>
  <div>
    <h3>接收的 MQTT 消息:</h3>
    <ul>
      <li v-for="(msg, index) in messages" :key="index">
        {{ msg.topic }}: {{ msg.content }}
      </li>
    </ul>
    <!-- <ul>
      <li v-for="(msg, index) in top2" :key="index">
        {{ msg.topic }}: {{ msg.content }}
      </li>
    </ul> -->
    <button @click="publishMessage">发送消息</button>
  </div>
</template>

<script>
import MQTTClient from '@/util/mqtt';

export default {
  data() {
    return {
      mqttClient: null,
      messages: [],
      top2:[]
    };
  },
  mounted() {
    this.initMQTT();
  },
  methods: {
    initMQTT() {
      this.mqttClient = new MQTTClient();
      
      // 连接到 MQTT 代理
       const url="ws://"+"你的地址"+":8083/mqtt"  //例如ws://172.18.14.167:8083/mqtt
      this.mqttClient.connect(url)
        .then(() => {
          console.log('订阅成功');
          // 订阅主题
          this.mqttClient.subscribe('kpmqqt-lims-data-top1', (message) => {
            this.messages.push(message);
          });
          // this.mqttClient.subscribe('kpmqqt-lims-data-top2', (message) => {
          //   this.top2.push(message);
          // });
        })
        .catch(err => {
          console.error('MQTT connection failed:', err);
        });
    },
    publishMessage() {
      if (this.mqttClient) {
        this.mqttClient.publish('kpmqqt-lims-data-top1', 'Hello from 测试Vue2!');
        // this.mqttClient.publish('kpmqqt-lims-data-top2', 'Hello from 测试!');
      } else {
        console.error('MQTT client not initialized');
      }
    }
  },
  beforeDestroy() {
    if (this.mqttClient) {
      this.mqttClient.disconnect();
    }
  }
};
</script>

四、或者直接在页面使用

<template>
  <div>
    <h3>接收的 MQTT 消息:</h3>
    <ul>
      <li v-for="(msg, index) in messages" :key="index">
        {{ msg.topic }}: {{ msg.content }}
      </li>
    </ul>
  </div>
</template>

<script>
import mqtt from 'mqtt';

export default {
  data() {
    return {
      client: null,
      messages: []
    };
  },
  mounted() {
    this.initMQTT();
  },
  methods: {
    initMQTT() {
      const options = {
        clientId: 'vue-client_' + Math.random().toString(16).substr(2, 8),
        clean: true,
        connectTimeout: 4000
      };
      const url="ws://"+"你的地址"+":8083/mqtt"  //例如ws://172.18.14.167:8083/mqtt
      this.client = mqtt.connect(url, options);

      this.client.on('connect', (e) => {
        this.subscribeTopics();
      });

      this.client.on('message', (topic, payload) => {
        this.messages.push({
          topic: topic,
          content: payload.toString()
        });
      });
    },
    subscribeTopics() {
      this.client.subscribe(['sensor/#'], { qos: 1 });
    }
  },
  beforeDestroy() {
    if (this.client) {
      this.client.end();
    }
  }
};
</script>

### 如何在 Vue 2 中使用 MQTT 实现消息订阅与发布 #### 安装依赖库 为了能够在 Vue 2 项目中集成并使用 MQTT 进行消息通信,首先需要安装 `mqtt` 库。可以通过 npm 或 yarn 来完成这一步骤。 ```bash npm install mqtt --save ``` 或者如果偏好使用 yarn: ```bash yarn add mqtt ``` #### 创建 MQTT 组件 创建一个新的 Vue 组件来处理所有的 MQTT 功能逻辑。这里展示了一个简单的例子,包含了连接、断开连接、订阅以及发布消息的方法[^2]。 ```javascript <template> <div class="mqtt-container"> <!-- UI Elements --> </div> </template> <script> import { onMounted, ref } from 'vue'; import mqtt from 'mqtt'; export default { name: "MqttComponent", setup() { const client = ref(null); const isConnected = ref(false); function connectToBroker(brokerUrl) { try { client.value = mqtt.connect(brokerUrl); // Connect to the broker using provided URL. isConnected.value = true; client.value.on('connect', () => console.log('Connected')); client.value.on('message', (topic, message) => handleIncomingMessage(topic, message)); } catch (error) { console.error(`Failed to connect: ${error.message}`); } } function subscribeTopic(topicName) { if (!isConnected.value || !client.value) return; client.value.subscribe(topicName, err => { if (err) { console.error(`Subscription failed: ${err.message}`); } else { console.log(`Subscribed to topic "${topicName}"`); } }); } function publishMessage(topicName, payload) { if (!isConnected.value || !client.value) return; client.value.publish(topicName, JSON.stringify(payload), error => { if (error) { console.error(`Publishing failed: ${error.message}`); } else { console.log(`Published message to topic "${topicName}"`); } }); } function disconnectFromBroker() { if (!isConnected.value || !client.value) return; client.value.end(); isConnected.value = false; console.log('Disconnected'); } function handleIncomingMessage(topic, message) { let parsedMsg = null; try { parsedMsg = JSON.parse(message.toString()); } catch (_) {} console.info(`Received Message On Topic "${topic}":`, parsedMsg ? parsedMsg : message.toString()); } onMounted(() => { // Initialize connection when component mounts or as needed based on application logic. connectToBroker('ws://test.mosquitto.org:8080'); // Replace with actual Broker address. // Example subscription after connecting successfully. setTimeout(() => subscribeTopic('example/topic'), 1000); }); return { isConnected, connectToBroker, subscribeTopic, publishMessage, disconnectFromBroker, }; }, }; </script> ``` 此代码片段展示了如何通过 WebSocket 协议建立到 MQTT 消息代理的连接,并实现了基本的消息收发操作。需要注意的是,在实际部署环境中应当替换掉示例中的公共测试服务器地址 (`ws://test.mosquitto.org`) 和默认主题名称 ('example/topic'),以匹配具体的应用需求和安全策略[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值