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);
				});
			},
		},

你可能感兴趣的:(前端,vue)