MQTT在Web开发中的应用

前文写了使用Docker部署了mqtt服务,今天来写一下,mqtt在web开发中的应用实例,希望能帮到大家,话不多说,直接开始。

一:脚手架安装mqtt

作者这里用的vue3的框架
直接上命令,npm安装或者pnpm进行安装。

npm install mqtt

二:使用mqtt

1.创建一个mqtt封装的js文件
比如我创建一个mqttTool.js
2.在js文件中引入mqtt

import * as mqtt from 'mqtt/dist/mqtt.min.js';

3.封装全局服务

const getMQTTUrl = () =>{
  let url = import.meta.env.VITE_APP_PHAR_MQTT;
  url ='ws://0.0.0.0:8000/mqtt';	//填写自己的mqtt服务ip
  console.info("当前 MQTT 地址为 " + url);
  return url 
}
//MQTT全局服务
export default class MQTTService {
    static instance = null;
    static get Instance() {
        if (!this.instance) {
            this.instance = new MQTTService();
        }
        return this.instance;
    }
    // 事件
    mitt = new mitt();
    //配置参数
    userOptions= {
        username: "mqttName",
        password: "test123",
        clientId: Math.random().toString(36).substr(2),
      };
    topics = [];//["test1", "dtest2"]; //需要订阅的主题
    // 和服务端连接的MQTT对象
    client = null;
    mqttUrl = getMQTTUrl() ;
    // 标识是否连接成功
    connected = false;
    // 记录重试的次数
    sendRetryCount = 0;
    // 重新连接尝试的次数
    connectRetryCount = 3;
    // 再次连接
    reconnect(){
        if (this.client==null){
            this.connect()
        }
    }
    //定义连接服务器的方法
    connect() { 
        let that =this;
        this.client = mqtt.connect(this.mqttUrl, this.userOptions);
        this.client.on("connect", (e) => {
            this.connected = true;
            // 重置重新连接的次数
            this.connectRetryCount = 3;
            that.topics.forEach((topic) => {
            that.client.subscribe(
                topic,
                { qos: 0, retain: 0 },
                (err, granted) => {
                  if (granted.length > 0) {
                    if (!err) {
                      console.log(`全局成功订阅主题:${granted[0].topic}`);
                    } else {
                      console.log("全局订阅主题失败", err);
                    }
                  }
                }
            );
          });
        });
        //失败重连
        this.client.on('error', (e) => {
            if (this.sendRetryCount < this.connectRetryCount-1){
                console.log("连接服务端失败:",e)
                this.connected = false;
                this.sendRetryCount++
                setTimeout(() => {
                    this.connect();
                }, 500 * this.connectRetryCount);
            }
          });

        this.client.on("message", (topic, message, packet) => {
          // 输出订阅的主题和消息
          console.log(`接收到主题为 ${topic} 的消息:`, message.toString());
          let res ={
              topic:topic,
              message:message,
              packet:packet
          }
        });
    }
    close(){ // 退出登录后断开连接
        if (this.client) {
            this.client.end(); //离开页面的时候  关闭mqtt连接
            this.client = null;
            console.log("关闭mqtt:");
          }
    }

    // 发送数据的方法
    send(data) {
        // 判断此时此刻有没有连接成功
        if (this.connected) {
            this.sendRetryCount = 0;
            try {
                this.client.publish(data.sender, data);
                  console.log("s发送到服务端:",data);
            } catch (e) {
                this.client.publish(data.sender, JSON.stringify(data)); console.log("O发送到服务端:",data)
            }
        } else {
            this.sendRetryCount++;
            setTimeout(() => {
                this.reconnect() // 重新连接
                this.client.publish(data.sender, JSON.stringify(data));
            }, this.sendRetryCount * 500);
        }
    }
    // 发送数据的方法2
       sendBySender(sender,data) {
        // 判断此时此刻有没有连接成功
        if (this.connected) {
            this.sendRetryCount = 0;
            try {
                this.client.publish(sender, data);
                  console.log("s发送到服务端:",data)
            } catch (e) {
                this.client.publish(sender, JSON.stringify(data)); console.log("O发送到服务端:",data)
            }
        } else {
            this.sendRetryCount++;
            setTimeout(() => {
                this.reconnect() // 重新连接
                this.client.publish(sender, JSON.stringify(data));
            }, this.sendRetryCount * 500);
        }
    }
    //自定义订阅内容
    setTopics(data){
        this.topics = data;
        this.close();
        this.connect();
    }
    getTopics(){
        return this.topics;
    }
    //添加订阅
    addTopic(topic){
      this.topics.push(topic);
      if (this.connected) {
        this.client.subscribe(
            topic,
            { qos: 0, retain: 0 },
            (err, granted) => {
              if (granted.length > 0) {
                if (!err) {
                  console.log(`全局成功订阅主题:${granted[0].topic}`);
                } else {
                  console.log("全局订阅主题失败", err);
                }
              }
            }
        );  
      }else{
        this.connect();
      }
    }
}

4.调用
在需要的vue中调用

import MQTTService from '/@/utils/mqttTool.js'
let mqttServe = MQTTService.Instance;

然后使用mqttServe对象调用相关方法即可。

  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
.NET C#是一种面向对象的编程语言,它是微软公司推出的一种多平台开发框架。基于.NET C#的开发平台可以支持Windows、Linux和macOS系统,能够开发桌面应用程序、web应用程序和移动应用程序等。 .NET C#具有很多优点。首先,它具有强大的跨平台能力,可以在不同的操作系统上运行,大大提升了开发的灵活性和效率。其次,C#语言本身具有简单易学的特点,语法规则清晰,对于初学者来说比较容易上手。同时,它也拥有许多强大的库和工具,可以大大减少开发的复杂性。此外,C#还支持其他语言相关的功能,如异步编程、LINQ等,使开发更加简洁高效。 基于.NET C#的开发框架也是非常强大的。它提供了丰富的类库和API,可以快速开发出高质量、可扩展的应用程序。对于数据库操作、网络通信、图形界面开发等常用功能,都有相应的库和工具来支持。同时,它还提供了一套灵活的开发模型和丰富的设计模式,可以满足不同项目的需求。 .NET C#还有一个优点是它具有良好的安全性和稳定性。在开发过程,C#会自动进行内存管理,减少内存泄漏和垃圾回收问题。而且,C#还提供了一些强大的安全特性,如类型安全、代码访问安全等,可以保证应用程序的安全性。 总之,基于.NET C#的开发平台是一种强大、灵活和高效的工具,可以帮助开发人员快速开发出高质量的应用程序。无论是开发桌面应用程序还是web应用程序,都可以选择.NET C#作为开发语言,来实现各种需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Devil枫

发财小手鼓励一下作者大大

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值