【问题标题】:MQTT.js - How to handle connection errors?MQTT.js - 如何处理连接错误?
【发布时间】:2018-03-21 17:59:10
【问题描述】:

我在使用 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));
    });
  }
}

【问题讨论】:

    标签: javascript angular typescript websocket mqtt


    【解决方案1】:

    我有一个非常相似的问题,client.on('error'..没有触发WebSocket连接错误,解决方案是:

    client.stream.on('error', (err) => { console.log('error', err); client.end() });

    【讨论】:

      猜你喜欢
      • 2020-02-21
      • 2021-07-30
      • 1970-01-01
      • 2022-06-02
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多