# 官网
# 注意事项
- 开启 Client 放在全局入口处,只连接一次 (
Vue
):
const onConnect = (cb?: () => void) => {
if (!Vue.prototype.PahoMQTTClient) {
let PahoMQTTClient = new window.mqtt.connect(`${WebSocket_URL}`, {
// 超时时间
connectTimeout: 4000,
// 认证信息
clientId,
username: mqttUserName,
password: mqttPassword,
// 心跳时间
keepalive: 60,
clean: true,
});
PahoMQTTClient.on('connect', () => {
console.log('MQTT onConnect--- success');
if (timer) clearTimeout(timer);
cb && cb();
});
PahoMQTTClient.on('reconnect', (err) => {
console.log('MQTT onConnect--- reconnect', err)
});
PahoMQTTClient.on('error', (err) => {
console.log('MQTT onConnect--- error', err);
if (timer) clearTimeout(timer);
PahoMQTTClient?.end(true);
PahoMQTTClient = null;
timer = setTimeout(() => {
onConnect(cb);
}, 2000);
});
Vue.prototype.PahoMQTTClient = PahoMQTTClient;
} else {
Vue.prototype.PahoMQTTClient.reconnect();
Vue.prototype.PahoMQTTClient.on('connect', () => {
console.log('MQTT onConnect--- success');
if (timer) clearTimeout(timer);
cb && cb();
});
}
}
onConnect();
/** 全局注册 Mqtt 实例连接方法 */
Vue.prototype.PahoMQTTClientConnect = onConnect;
};
- 避免重复监听
protected destroyed() {
if (this.timer) clearTimeout(this.timer);
try {
this.PahoMQTTClient.removeAllListeners();
} catch (e) {
console.log("PahoMQTTClient.end_err", e);
}
}
- 监听回调消息
let msg: string | null = null;
this.PahoMQTTClient.on('message', (topic, message, packet) => {
// 根据 tipic 判断订阅调用不通方法
msg = message.toString();
console.log('订阅消息-RegisteredMqttCbMixin: registeringCb: ' + topic + ' : ' + msg);
// 调用方法传递 json
todo(JSON.parse(msg));
});