mqtt.js 官网地址: MQTT
若是采用JS使用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()
})
import mqtt from 'mqtt'
data() {
return {
client: {},
mtopic: '订阅的主题',
msg: '返回的消息'
};
},
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;
});
}
<el-button @click="publishTopic()">el-button>
publishTopic() {
this.client.publish('订阅的主题名称', JSON.stringify(
{
// 条件
"deptAreaId": this.currentUser.deptAreaId,
"code": 1,
}
));
},
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);
...
}
},
},