VUE集成MQTT

该代码示例展示了如何在JavaScript中安装和使用mqtt.js库来连接MQTT服务器,处理连接、消息和重连事件。它还包含了发布和订阅主题的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装依赖

npm install mqtt@2.18.9 --save

代码集成

JS工具
mqtt-utils.js


import mqtt from "mqtt";

export default {
	MQTT_SERVER: "ws://XXXXXXX:8083/mqtt",//ws的端口是8083  TCP端口是1883
	MQTT_CONFIG: {
		username: "XXXX",
		password: "XXXXX",
		clientId: "WEB_01",
		keepAlive: 60,
		cleanSession: true,
		clear: true
	},
	mmClient: null,

	handleCon(clientId) {
		console.log('==handleCon==');
		this.mClient = mqtt.connect(this.MQTT_SERVER, this.MQTT_CONFIG);

		// mqtt连接
		this.mClient.on("connect", (e) => {
			console.log(e, "mqtt连接成功!");
			let topic1 = "device/+/send";
			// // let topic2 = "test2";
			let qos1 = 0;
			// // let qos2 = 0;
			// this.subTopic(this.mClient, [topic1, topic2], [qos1, qos2]);
			this.subTopic([topic1], [qos1]);

		});

		// 消息处理
		this.mClient.on("message", (topic, message) => {
			console.log("收到消息", topic, message);
			// let value = message.buffer
			var uint8_msg = new Uint8Array(message);
			var message = String.fromCharCode.apply(null, uint8_msg);
			console.log(message);
		})

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

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


	},

	/**
	 * 【通用】发布话题
	 *
	 * @param mClient
	 * @param topic
	 * @param qos
	 * @param msg
	 */

	pubTopic(topic, qos, msg) {
		console.log('=======pubTopic=====')
		this.mClient.publish(topic, msg, qos, err => {
			if (!err) {
				console.log("发布成功!");
			} else {
				console.log("发布失败!", err);
			}
		})
	},


	/**
	 * 【通用】订阅话题
	 *
	 * @param mClient
	 * @param topic
	 * @param qos
	 */
	subTopic(topic, qos) {
		this.mClient.subscribe(topic, qos, err => {
			if (!err) {
				console.log("订阅成功!");
			} else {
				console.log("订阅失败!", err);
			}
		})
	}
}

VUE页面集成

this.initMqtt();
MqttUtils.pubTopic("device/123456789/recive", 1, "123123");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值