MQTT(Message Queuing Telemetry Transport)作为一种轻量级、开放、灵活、简单、易于实现的通信协议。它基于发布/订阅(Publish/Subscribe)模式的消息传输协议,在上位机和硬件设备间通信时经常用到。虽然在嵌入式软件一般使用C++来编码,但是难免有web端直接与设备交互的应用场景,本文将介绍mqtt本地服务部署和基于Vue的web端应用使用mqtt的全过程。

mqtt部署

EMQX(Erlang MQTT Broker)是一个用于支持 mqtt 的开源消息代理软件,这里我们用他来作为本地的mqtt 服务器。可以从这里下载,运行步骤如下

安装步骤

  • emqxbin文件夹下运行emqx start
    在这里插入图片描述
  • 进入服务端可视化面板http://127.0.0.1:18083
    在这里插入图片描述
  • 下载mqttx,这是mqtt的客户端工具,在调试的时候比较方便和清楚。下载。新建连接,连接到我们刚才启动的服务上。
    在这里插入图片描述
  • 测试一下是否连接上
    在这里插入图片描述

注意事项

  1. 运行emqx报错、启动不了
    原因可能是emqx文件夹所在的路径有中文或空格,导致服务不能启动。

  2. 服务启动后控制面板报错url not found
    原因是服务端口被占用了,emqx默认监听的是8081端口,找到下面这个文件,把监听的端口改成空闲的端口即可。
    在这里插入图片描述
    这里改成了8089
    在这里插入图片描述

Vue连接mqtt

  1. 安装mqtt的依赖
npm install mqtt
  1. 使用mqtt.js来建立MQTT连接并监听订阅。以下是一个简单的Vue组件示例:
<template>
  <div id="app">
  </div>
</template>

<script>
import mqtt from "mqtt";
import * as mqttUtils from "./utils/mqtt";

export default {
  name: "App",
  data() {
    return {
      config: {
        username: "admin",
        password: "123456",
        clientId: "code_dev_ui" + new Date().getTime(),
        keepAlive: 60,
        cleanSession: true,
        clear: true,
      },
      client: null,
      brokerUrl: "ws://localhost:8083/mqtt",
      topics: ["mqtt/#"],
  },
  mounted() {
    this.handleConnection();
  },
  methods: {
    /**
     * 建立连接
     */
    handleConnection() {
      var client = mqtt.connect(this.brokerUrl, this.config);
      this.client = client;
      // 保存至全局
      this.$store.dispatch("connectSucc", client);

      client.on("connect", (e) => {
        console.log(e, "mqtt连接成功!");
        mqttUtils.sub(client, this.topics, 0);
      });

      // 消息处理
      client.on("message", (topic, message) => {
        var text = new TextDecoder().decode(message);
        const info = eval("(" + text + ")");
        console.log("收到消息app:", topic, info);
        this.mqttControl(topic, info);
      });

      // 断线重连
      client.on("reconnect", (error) => {
        console.log("正在重连:", new Date().getTime(), error);
      });

      // 连接失败
      client.on("error", (err) => {
        console.log("mqtt连接失败!{}", err);
        client.end();
      });
    },

    /**
     * mqtt消息接收 事件回调
     */
    mqttCallBack(topic, info) {
      console.log(topic,info);
   },
};
</script>

3.Java后端连接使用mqtt配置如下

mqtt:
  hostUrl: ws://localhost:8083/mqtt
  username: admin
  password: public
  client-id: MQTT-CLIENT-DEV2
  cleanSession: true
  reconnect: true
  timeout: 100
  keepAlive: 80
  defaultTopic: pop
  defaultTopics: mqtt
  serverTopic: mqtt
  isOpen: true
  qos: 0
  qoss: 0,0
GitHub 加速计划 / vu / vue
109
18
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:3 个月前 )
9e887079 [skip ci] 1 年前
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 1 年前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐