小编Tao*_*Tao的帖子

MQTT.js - 如何处理连接错误?

我很难检测 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 …
Run Code Online (Sandbox Code Playgroud)

javascript websocket mqtt typescript angular

5
推荐指数
1
解决办法
3972
查看次数

标签 统计

angular ×1

javascript ×1

mqtt ×1

typescript ×1

websocket ×1