1、下载mqtt.js
npm install mqtt --save
2、配置mqtt账号、密码、请求链接
//MQtt.js
export const MQTTIP = "wss:xxxxxxxxxxxx"; //聊天接口
export const USERNAME = "admin"; //账号
export const PASSWORD = "admin"; //密码
3、在需要的页面引入
//xxx.vue
import mqtt from "mqtt";
import { MQTTIP,USERNAME, PASSWORD } from "../../utils/MQtt";
function S() {
return (((1 + Math.random()) * 0x10000) | 0).toString(32).substring(1);
}
let MathRandom =
S() + S() + "-" + S() + "-" + S() + "-" + S() + "-" + S() + S() + S();
let MqttUserId = "clientid-" + MathRandom;
var client;
const options = {
connectTimeout: 40000, //链接超时时间
clientId: MqttUserId, //这个id最好的是随机的
username: USERNAME, //账号
password: PASSWORD, //密码
clean: true,
keepalive: 24000 //心跳
};
client = mqtt.connect(MQTTIP, options);
export default {
data() {
return {
mtopic: "xxxxxxx", //订阅的主题
},
created() {
this.myMqtt();
},
methods: {
// 获取当前消息
myMqtt() {
// 连接mqtt
client.on("connect", e => {
console.log("连接成功");
client.subscribe(this.mtopic, err => {
if (!err) {
console.log("订阅成功:" + this.mtopic);
}
});
});
// 接收推送消息
client.on("message", (topic, message) => {
//这里会打印三次,导致下面调用接口的时候回调三次,做了一个处理,反正问题解决了,不知道是不是自己的方法用错了
for (var i = 0; i < 1; i++) {
console.log("接收推送信息:", message.toString(), "主题", topic);
}
});
// 断开发起重连
client.on("reconnect", error => {
console.log("正在重连...", error);
});
// 链接异常处理
client.on("error", error => {
console.log("连接失败...", error);
});
},
}
//发送消息
handleclick: function() {
this.client.publish(this.mtopic, xxxx(这里是回复的消息));
}
}