Javascript MQTT.js-如何处理连接错误?
我很难用MQTT.js检测连接错误 我尝试在角度服务中使用它,当服务器运行时,与服务器的连接和通信似乎可以正常工作,但是Javascript MQTT.js-如何处理连接错误?,javascript,angular,typescript,websocket,mqtt,Javascript,Angular,Typescript,Websocket,Mqtt,我很难用MQTT.js检测连接错误 我尝试在角度服务中使用它,当服务器运行时,与服务器的连接和通信似乎可以正常工作,但是client.on('error',…)从不触发 我通过将错误回调附加到client.stream来检测连接时的错误,但是stream似乎是私有属性,因为它没有在正式的TypeScript定义中公开,所以不确定这是否是正确的方法 但我仍然无法工作的是当连接丢失时的错误,没有任何错误处理程序启动。相反,浏览器控制台记录未处理的websocket错误 示例代码: import {
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));
});
}
}
我在
客户端遇到了一个非常类似的问题。在('error')上,
没有触发WebSocket连接错误,解决方案是:
client.stream.on('error',(err)=>{
console.log('error',err);
client.end()
});