vue项目中使用mqtt的方法

MQTT是轻量级的发布/订阅式消息传输,旨在为低带宽和不稳定的网络环境中的物联网设备提供可靠的网络服务。

MQTT协议通讯实现客户端与服务器端间的通讯;

安装:cnpm install mqtt --save

mqtt整体代码:

import mqtt from "mqtt";
	data() {
			return {
				//与后台约定好的主题
				publish: {
					topic: "",
					kkno: "",
				},
			}
		},
		mounted() {
			this.connect();
		},
		methods: {
			//连接服务器
			connect() {
				const MQUrl = `wss://localhost:8080/mqtt`;
				const clientId = `mqtt_${Math.random().toString(16).slice(3)}`;
				this.client = mqtt.connect(MQUrl, {
					clientId,
					clean: true,
					cleanSession: false,
					connectTimeout: 4000,
					username: "账号",
					password: "密码",
					reconnectPeriod: 1000,
				});
				this.client.on("connect", (e) => {
					console.log("成功连接服务器:", e);
					//订阅
					this.client.subscribe(
						this.publish.topic + this.publish.kkno,
						(error) => {
							if (!error) {
								console.log("订阅成功");
							} else {
								console.log("订阅失败");
							}
						}
					);
				});
				//重新连接
				this.reconnect();
				//是否已经断开连接
				this.MqError();
				//监听获取信息
				this.getMessage();
			},
			//监听接收消息
			getMessage() {
				this.client.on("message", (topic, message) => {
					if (message) {
						const res = JSON.parse(message.toString());
						console.log(res, "收到数据");
					}
				});
			},
			//监听服务器是否连接失败
			MqError() {
				this.client.on("error", (error) => {
					console.log("连接失败:", error);
					this.client.end();
				});
			},
			//断开连接
			endConnect() {
				this.client.end();
				this.client = null;
				console.log("服务器已断开连接!");
			},
			//监听服务器重新连接
			reconnect() {
				this.client.on("reconnect", (error) => {
					console.log("正在重连:", error);
				});
			},
		},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值