参数配置
this.data = {
client: null,
host: "mqtt.server.com",
subTopic: "Hello/",
pubTopic: "Hello/",
pubMsg: "Hello! I am from Alipay miniprogram",
receivedMsg: "",
mqttOptions: {
username: "user",
password: "password",
reconnectPeriod: 1000,
connectTimeout: 5 * 1000,
keepalive: 5,
my: my,
},
使用示例
connect(mqtt, url, subTopic)
{
try {
console.log("conenctBtnText", "连接中...");
const clientId = new Date().getTime();
this.data.subTopic = subTopic
this.data.pubTopic = subTopic
this.data.server = url
let server = `wss://${url}:8084/mqtt`
server = `alis://${url}:8084/mqtt/`
server = `wxs://${url}:8084/mqtt`
console.log("conenct...", server);
this.data.client = mqtt.connect(server, {
...this.data.mqttOptions,
clientId,
});
this.data.client.on("connect", () => {
console.log("conenctBtnText", "连接成功");
this.data.client.on("message", (topic, payload) => {
const currMsg = this.data.receivedMsg ? `<br/>${payload}` : payload;
console.log("receivedMsg", this.data.receivedMsg.concat(currMsg));
});
this.data.client.on("error", (error) => {
console.log("conenctBtnText", "连接");
console.log("onError", error);
});
this.data.client.on("reconnect", () => {
console.log("conenctBtnText", "正在重连接");
console.log("reconnecting...");
});
this.data.client.on("offline", () => {
console.log("conenctBtnText", "连接");
console.log("onOffline");
});
if (this.data.client) {
this.data.client.subscribe(subTopic, '{qos: 2}')
console.log(`成功订阅主题:${this.data.subTopic}`);
uni.showToast({
title: '欢迎光临',
icon: 'none',
duration: 300
});
return
}
});
} catch (error) {
console.log("conenctBtnText", "连接");
console.log("mqtt.connect error", error);
}
}