赞
踩
package.json
{
"name": "mqtt-demo",
"version": "1.0.4",
"description": "MQTT.js 的使用示例",
"main": "main.js",
"dependencies": {
"mqtt": "^3.0.0"
},
"devDependencies": {
"npm-pack-zip": "^1.3.0"
},
"scripts": {
"pack": "npm-pack-zip"
},
"author": "",
"license": "ISC",
"id": "mqtt-demo",
"displayName": "mqtt-demo",
"keywords": [
"mqtt",
"websocket"
],
"dcloudext": {
"category": [
"uni-app前端模板",
"uni-app前端项目模板"
]
}
}
mqtt-utils.js
import mqtt from 'mqtt/dist/mqtt.js'
import Emitter from "../common/emitter.js"
export default {
// #ifdef H5
MQTT_SERVER: "ws://ip:8083/mqtt", //ws的端口是8083 TCP端口是1883
// #endif
// #ifdef MP-WEIXIN||APP-PLUS
MQTT_SERVER: "wx://ip:8083/mqtt", //ws的端口是8083 TCP端口是1883
// #endif
MQTT_CONFIG: {
username: "账号",
password: "密码",
clientId: "H5_" + new Date().getTime(),
keepAlive: 60,
cleanSession: true,
clear: true,
},
mTopicList: [],
mClient: null,
mConState: 0, //0 未连接 1:正在连接 2:连接成功
init() {
},
subAllTopic() {
for (var item of this.mTopicList) {
this.subTopic(item);
}
},
async handleCon() {
if (this.mConState != 0) return;
console.log("==handleCon==");
this.mClient = mqtt.connect(this.MQTT_SERVER, this.MQTT_CONFIG);
// mqtt连接
this.mClient.on("connect", e => {
console.log("mqtt连接成功!");
this.mConState = 2;
this.subAllTopic();
});
// 消息处理
this.mClient.on("message", (topic, message) => {
console.log("收到消息", topic, message);
if (topic.indexOf("$SYS/brokers/") == 0) {
//在线离线消息
Emitter.$emit("MQTT-ONLINE", topic);
Emitter.$emit("MQTT-MAIN-ONLINE", topic);
} else {
var msg = {
data: message,
topic: topic
};
Emitter.$emit("MQTT-MSG", msg);
}
});
// 断线重连
this.mClient.on("reconnect", () => {
console.log("正在重连!!!");
this.mConState = 1;
});
// 连接失败
this.mClient.on("error", () => {
console.log("mqtt连接失败!!!");
this.mClient.end();
this.mConState = 0;
});
},
/**
* 【通用】发布话题
*
*/
pubTopic(topic, msg) {
if (!this.mClient) return;
console.log("topic=>" + topic)
this.mClient.publish(topic, msg, 1, (err) => {
if (!err) {
console.log("发布成功!");
} else {
console.log("发布失败!", err);
}
});
},
/**
* 【通用】订阅话题
*/
subTopic(topic) {
if (!this.mClient) return;
this.mClient.subscribe(topic, 1, (err) => {
if (!err) {
console.log("订阅成功!=>" + topic);
} else {
console.log("订阅失败!", err);
}
});
},
/**
* 【通用】订阅话题
*/
addTopic(topic) {
if (this.mTopicList.indexOf(topic) == -1) {
if (this.mConState == 2) {
this.subTopic(topic);
}
this.mTopicList.push(topic);
}
},
closeCon() {
this.mConState = 0;
this.mClient.end();
},
};
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。