前端使用mqtt实现实时页面

445 阅读2分钟

MQTT是什么

首先是最为普遍的关于mqtt的介绍

Mqtt是一种基于发布/订阅模式的轻量级消息传输协议,专门针对低带宽和不稳定网络环境的物联网应用而设计,可以用极少的代码为联网设备提供实时可靠的消息服务。MQTT 协议广泛应用于物联网、移动互联网、智能硬件、车联网、智慧城市、远程医疗、电力、石油与能源等领域

mqtt主要是发布订阅模式 客户端既可以向订阅了的主题发布消息,也可以订阅接收特定主题上的消息

MQTT怎么用

mqtt 主要是采用订阅主题 主题通过 / 来区分层级,类似于 URL 路径 例如 topic/user 就是订阅topic下的user主题 。并且主题订阅严格区分大小写

MQTT 主题支持以下两种通配符:+ 和 #。
- +:表示单层通配符,例如 a/+ 匹配 a/x 或 a/y。
- #:表示多层通配符,例如 a/# 匹配 a/x、a/b/c/d

MQTT的使用

我看有些是直接引入 mqtt 但是我的引入mqtt报错 所以我引入了connect方法

import { connect } from "mqtt";
import {Message} from "element-ui"
let client = {};
//连接服务器
/**
 * params:
 * @options 参数
 */
export function connectFn({ username, password, url, topic }, callBack) {
    let options = {
        username,
        password,
        cleanSession: false,
        keepAlive: 60,
        clientId: "mqttjs_" + Math.random().toString(16).substr(2, 8),
        connectTimeout: 4000,
    };
    client = connect(url, options);
    client.on("connect", (e) => {
        Message.success("成功连接服务器")
        console.log("成功连接服务器:", e);
        //订阅主题
        client.subscribe(topic, { qos: 1 }, (err) => {
            if (!err) {
                Message.success("订阅成功")
                console.log("订阅成功");
            } else {
                Message.error("消息订阅失败!")
                console.log("消息订阅失败!");
            }
        });
    });
    //重新连接
    reconnect();
    //是否已经断开连接
    mqttError();
    //监听获取信息
    getMessage(callBack);
};
//发布消息 @topic主题  @message发布内容
export function publish(topic, message) {
    if (!client.connected) {
        console.log("客户端未连接");
        return;
    }
    client.publish(topic, message, { qos: 1 }, (err) => {
        if (!err) {
            console.log("主题为" + topic + "发布成功");
        }
    });
}
//监听接收消息
function getMessage(callBack) {
    client.on("message", (topic, message) => {
        if (message) {
            callBack(topic, message)
        }
    });
}
//监听服务器是否连接失败
function mqttError() {
    client.on("error", (error) => {
        console.log("连接失败:", error);
        client.end();
    });
}
//取消订阅
export function unsubscribe(topicList) {
    client.unsubscribe(topicList, (error) => {
        console.log("主题为" + topicList + "取消订阅成功", error);
    });
}
//断开连接
export function unconnect() {
    client.end();
    client = null;
    Message.warning("服务器已断开连接!")
    console.log("服务器已断开连接!");
}
//监听服务器重新连接
function reconnect() {
    client.on("reconnect", (error) => {
        console.log("正在重连:", error);
    });
}

在vue中使用:

import {connectFn ,unsubscribe ,unconnect} from "@/utils/mqtt" ;
data(){
    return {
        topicList:["topic/username", "topic/class"]
    }
},
methods:{
    getMessage(topic, message){
     if (message) {
          console.log("收到来着", topic, "的信息", message.toString());
          const res = JSON.parse(message.toString());
          switch (topic) {
            case "topic/username":
              this.username = res;
              break;
            case "topic/class":
              this.class = res;
              break;
            default:
              return;
          }
          }
    }
},
  mounted() {
    connectFn({
      url:"ws://ip:port/mqtt",
      username: "username",
      password: "123456",
      topic :["topic/#"]
    },this.getMessage);
  },
  beforeDestroy(){
    unsubscribe(this.topicList)
    unconnect();
  }

实现实时订阅以后 当订阅了的主题有新的数据消息发来 前端页面就会收到,

至此已经实现了前端和mqtt的即时通信 等我发现其他的问题再来修改 也欢迎各位大佬指正