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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue使用MQTT,你可以使用MQTT.js库来实现。以下是一些基本步骤: 1. 安装MQTT.js库:在你的Vue项目使用npm或yarn安装mqtt库: ``` npm install mqtt ``` 或 ``` yarn add mqtt ``` 2. 导入MQTT库:在你的Vue组件,导入mqtt库: ```javascript import mqtt from 'mqtt'; ``` 3. 创建MQTT客户端:在Vue组件,创建一个MQTT客户端实例,并连接到MQTT代理: ```javascript const client = mqtt.connect('mqtt://mqtt.example.com'); // 替换为你的MQTT代理地址 ``` 4. 监听MQTT连接状态:可以监听MQTT客户端的连接状态,以便在连接成功或失败时进行处理: ```javascript client.on('connect', function () { console.log('Connected to MQTT broker'); }); client.on('error', function (error) { console.error('MQTT connection error:', error); }); ``` 5. 订阅和接收消息:可以订阅一个或多个主题,并在接收到消息时进行处理: ```javascript client.subscribe('topic1'); client.on('message', function (topic, message) { console.log('Received message:', message.toString()); }); ``` 6. 发布消息:可以使用`client.publish()`方法发布消息到指定的主题: ```javascript client.publish('topic1', 'Hello MQTT'); ``` 这些是基本的使用步骤,你可以根据需要进行扩展和自定义。记得在不需要时断开MQTT连接: ```javascript client.end(); ``` 请注意,这只是一个简单的示例,实际使用时可能需要处理更多的逻辑和错误处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值