Tao*_*Tao 5 javascript websocket mqtt typescript angular
我很难检测 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));
});
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我有一个非常类似的问题,client.on('error'..没有触发 WebSocket 连接错误,解决方案是:
client.stream.on('error', (err) => {
console.log('error', err);
client.end()
});
| 归档时间: |
|
| 查看次数: |
3972 次 |
| 最近记录: |