前端mqtt封装

2 篇文章 0 订阅

我们继续上一篇论文的内容继续

上一篇
对mqtt进行封装
之前用paho-mqtt这个模块,大概了解了mqtt的用法下面我用mqtt模块进行封装
以下代码可以直接复制到一个js文件中

import mqtt_module from 'mqtt'

const Mqtt = function (url) {
    this.mqtt = mqtt_module
    this.random = getGuid32;
    this.clientId = getGuid32();
    let options = {
        clientId: this.clientId,
        username: 'test',
        password: 'test',
        connectTimeout: 100,
        keepalive: 100
    }
    this.client = this.mqtt.connect("ws://" + url + "/mqtt", options)
    // 重连次数 超5次就算了
    this.reconnectNum = 0
    // 连接
    this.link = function () {
        return new Promise((resolve, reject) => {
            this.client.on('connect', e => {
                console.log('-----------------------链接成功-----------------------')
                resolve(this.client)
            })
            this.client.on('reconnect', error => {
                this.reconnectNum++
                if (this.reconnectNum >= 10) this.client.end(true)
                console.log('正在重连:', error)
            })
            this.client.on('error', error => {
                console.log('订阅失败', error)
            })
        })
    }
    this.subscribe = function (topic, options) {
        this.client.subscribe(topic, options, (err) => {
            if (!err) {
                console.log('-----------------------'+topic+'订阅成功-----------------------')
            } else {
                throw new Error(err)
            }
        })
    }
    this.publish = function (topic, sendMsg, options) {
        this.client.publish(topic, JSON.stringify(sendMsg), options, (err, a) => {
            if (!err) {
                console.log('-----------------------'+topic+'发送成功-----------------------')
            } else {
                throw new Error(err)
            }
        })
    }
    this.message = function (callback) {
        this.client.on('message', (topic, message) => {
            let data = JSON.parse(message.toString())
            callback(data, topic)
        })
    }
    // 关闭
    this.close = function () {
        this.client.end(true)
    }
}

export default Mqtt

function getGuid32() {
    var rt_str = String.fromCharCode(65 + Math.floor(Math.random() * 26));
    for (var i = 0; i < 31; ++i) {
        var num = Math.floor(Math.random() * (26 + 26 + 10));
        var ch_str;
        if (num < 10) {
            ch_str = num.toString();
        } else if (num < 10 + 26) {
            ch_str = String.fromCharCode(65 + num - 10);
        } else {
            ch_str = String.fromCharCode(97 + num - 10 - 26);
        }
        rt_str += ch_str;
    }
    return rt_str;
}

我们看看怎么使用

import Mqtt from "../utils/mqtt/mqtt";//将刚才的js引入
var mqtt = new Mqtt("xxx.xxx.xx.xx:xxxx");//里面写上ip和端口
var topic = "SpeedRegulation/CompayInfo/GetAllSiteData";//这里就是主题
mqtt.link().then((client) => {//封装成promsie方便使用  
	//client这里保留了原生的client函数和用法
  var sendMess = { //这就是要传给后端的参数
    MessageId: topic,
    TopicId: topic,
    Time: new Date().getTime(),
    ClientID: mqtt.clientId,//这个mqtt是生成随机生成的随机数
    //当然要想申请新的随机数可以mqtt.random()
  };
  mqtt.subscribe(topic);//订阅主题
  mqtt.subscribe(topic + "/" + mqtt.clientId);//订阅主题
  mqtt.publish(topic, sendMess,{qos:0})//向某个主题发送消息
  mqtt.message(function (data, topic) {//接收消息,跟据返回的主题可以确定是哪个主题给的消息
    console.log(data, topic);
  });
});

与promsie结合的mqtt,要是有问题希望即使联系我,我进行改正

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
MQTT(Message Queuing Telemetry Transport)是一种轻量级的通信协议,用于在低带宽和不稳定的网络环境下,实现物联网设备之间的即时通信。前端可以使用MQTT来订阅消息,以获取实时的数据更新。 首先,我们需要引入MQTT的客户库。一般来说,我们可以使用开源的Paho MQTT客户库来实现。可以通过直接下载js文件,或者使用npm安装。 接下来,我们需要创建一个MQTT的客户实例。通过指定MQTT broker的地址、口和协议,我们可以建立与broker的连接。同时,我们还需要指定一个client ID,用于标识当前的客户。 一旦连接建立成功,我们可以通过使用subscribe()方法来订阅特定的主题(topic)。主题可以看做是一种消息的分类或者标签。当有新的消息发布到这个主题上时,前端会收到相应的消息回调。 在订阅成功后,前端就可以接收到来自broker的实时消息了。前端可以定义一个回调函数,用于处理接收到的消息。这个回调函数可以根据消息的内容,更新页面上的相关数据或者执行相应的操作。 如果前端不再需要订阅某个主题,可以使用unsubscribe()方法来取消订阅。 需要注意的是,由于前端是在浏览器中运行的,它的网络连接通常是不稳定的。因此,在实际应用中,我们一般会在连接断开时,尝试重新连接,以确保能够持续接收到实时消息。 总的来说,前端通过MQTT订阅消息,可以实现实时数据的获取和展示,在物联网应用、实时监控等场景中有着广泛的应用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值