Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript MQTT.js-如何处理连接错误?_Javascript_Angular_Typescript_Websocket_Mqtt - Fatal编程技术网

Javascript 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 {

我很难用MQTT.js检测连接错误

我尝试在角度服务中使用它,当服务器运行时,与服务器的连接和通信似乎可以正常工作,但是
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()
});