[英]MQTT.js - How to handle connection errors?
我很难用 MQTT.js 检测连接错误。
我试图在 Angular 服务中使用它,当服务器运行时,与服务器的连接和通信似乎工作正常,但client.on('error', ...)
永远不会触发。
我在连接时通过将错误回调附加到client.stream
设法检测到错误,但stream
似乎是一个私有属性,因为它没有在官方 TypeScript 定义中公开,所以不确定这是否真的是正确的方法.
但是我仍然无法工作的是连接丢失时的错误,没有任何错误处理程序触发。 相反,浏览器控制台会记录未处理的 websocket 错误。
示例代码:
import { Injectable } from '@angular/core';
import { connect, MqttClient } from 'mqtt';
import * as msgpack5 from 'msgpack5';
import { environment } from '../../environments/environment';
@Injectable()
export class MqttService {
private client: MqttClient;
private msgpack: msgpack5.MessagePack;
constructor() {
this.msgpack = msgpack5();
this.client = connect(`ws://${environment.host}:8001/mqtt`);
this.client.on('connect', () => {
console.log('connected');
this.client.subscribe('foo');
});
this.client['stream'].on('error', (error) => {
// fires when connection can't be established
// but not when an established connection is lost
console.log('stream', error);
this.client.end();
});
this.client.on('error', (error) => {
console.log('client', error); // never fires
});
this.client.on('message', (topic, payload) => {
console.log(topic, this.msgpack.decode(payload));
});
}
}
我有一个与client.on('error'..
没有触发 WebSocket 连接错误非常相似的问题,解决方案是:
client.stream.on('error', (err) => { console.log('error', err); client.end() });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.