1、下载mqtt.js
npm install mqtt --save
2、配置mqtt账号、密码、请求链接
export const MQTTIP = "wss:xxxxxxxxxxxx";
export const USERNAME = "admin";
export const PASSWORD = "admin";
3、在需要的页面引入
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,
username: USERNAME,
password: PASSWORD,
clean: true,
keepalive: 24000
};
client = mqtt.connect(MQTTIP, options);
export default {
data() {
return {
mtopic: "xxxxxxx",
},
created() {
this.myMqtt();
},
methods: {
myMqtt() {
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(这里是回复的消息));
}
}
下面是完成的截图(其中需要聊天记录接口以及聊天列表的list接口,然后做两次监听,一个监听列表一个监听当前聊天窗口)
以上。
|