在vue中使用mqtt.js

mqtt.js 官网地址: MQTT
若是采用JS使用MQTT,详见

1. 脚手架中安装mqtt

npm install mqtt --save

官网例子:

const mqtt = require('mqtt')
const client  = mqtt.connect('mqtt://test.mosquitto.org')

client.on('connect', function () {
	client.subscribe('presence', function (err) {
		if (!err) {
			client.publish('presence', 'Hello mqtt')
		}
	})
})

client.on('message', function (topic, message) {
	// message is Buffer
	console.log(message.toString())
	client.end()
})

2. 在vue文件中引入mqtt

import mqtt from 'mqtt'

3. 在data中声明client对象

data() {
	return {
		client: {},
		mtopic: '订阅的主题',
		msg: '返回的消息'
	};
},

4. 在mounted钩子中建立连接

mounted() {
	this.client = mqtt.connect("ws://ip:port", {
		username: "admin",
		password: "password",
		keepalive: 15 //心跳保持时间(秒)
	});
	
	this.client.on("packetreceive", (e) => {
		if (e.cmd == "pingresp") {
			//console.log("发送心跳", e);
		}
	});
	
	// 连接成功后 - 订阅主题
	this.client.on("connect", e =>{
		console.log("连接成功");
		this.client.subscribe(this.mtopic, (err) => {
			if (!err) {
				console.log("订阅成功:" + this.mtopic);
			}
		});
	});
	
	// 连接成功后 - 返回的订阅内容
	this.client.on("message", (topic, message) => {
		this.msg = message;
	});
}

5. 发布消息

<el-button @click="publishTopic()"></el-button>
publishTopic() {
	this.client.publish('订阅的主题名称', JSON.stringify(
		{
			// 条件
			"deptAreaId": this.currentUser.deptAreaId,
			"code": 1,
		}
	));
},

6. 实际案例

data() {
	return {
		client: {},
		parkTopic: "",
		parkPrefix: "parking/",
	};
},
mounted() {
	// 订阅的主题
	this.parkTopic = this.parkPrefix + this.currentUser.parkingId;
	// 连接MQTT
	this.connectMqtt();
},
methods: {
	connectMqtt() {
		// "ws://192.168.0.101:15675/ws"
		let wsUrl = process.env.VUE_APP_WS_URL || "ws://" + location.hostname + ":15675/ws";
	
		// MQTT 连接
		this.client = mqtt.connect(wsUrl, {
			username: process.env.VUE_APP_WS_USER || "admin",
			password: process.env.VUE_APP_WS_PWD || "123456",
			keepalive: 15//心跳保持时间(秒)
		});
		
		this.client.on("packetreceive", (e) => {
			if (e.cmd == "pingresp") {
				//console.log("发送心跳", e);
			}
		});
	
		// 连接成功后 - 订阅主题
		this.client.on("connect", e => {
			console.log("连接成功", Date.now());
			this.onSubscribe();
		});
	
		// 连接成功后 - 返回的订阅内容
		this.client.on("message", (topic, message) => {
			this.onMessage(topic, message);
		});
	},
	// 订阅主题
	onSubscribe() {
		
		this.client.subscribe(this.parkTopic, (err) => {
			if (!err) {
				console.log("订阅派车单成功:" + this.parkTopic);
			}
		});
	},
	// 接收消息
	onMessage(topic, message) {
		if (topic.indexOf(this.parkTopic) > -1) {
			var msg = JSON.parse(message);
			...
		}
	},
},
		

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值