mqtt请求不断创建连接

 问题描述:

新增页面, clientID自动随机创建.

第一次一次点击测试连接,则请求正常;页面保持不变,继续第二次再点击发起请求,则会不断触发重连请求;

按钮:

<button nz-button nzType="primary" class="submit-button" (click)="testWSUrl()">测试连接 </button>

JS请求代码: 

  // Websocket测试连接
  public testWSUrl() {

    // 连接信息
    const connection = {
      host: 'xx.xx.xxx.xxx',
      port: '8083',
      endpoint: '/mqtt',
      clean: true, // 保留会话
      connectTimeout: 4000, // 超时时间
      reconnectPeriod: 4000, // 重连时间间隔
      // 认证信息
      clientId: 'mqttx_55756bc0',
      username: 'admin',
      password: '123456',
    };

    let client = {
      connected: false,
    };

    this.createConnection(connection, client)

  }

  // 创建连接
  // 连接字符串, 通过协议指定使用的连接方式
  // ws 未加密 WebSocket 连接
  // wss 加密 WebSocket 连接
  // mqtt 未加密 TCP 连接
  // mqtts 加密 TCP 连接
  // wxs 微信小程序连接
  // alis 支付宝小程序连接
  createConnection(connection, client) {
    const { host, port, endpoint, ...options } = connection;
    const connectUrl = `ws://${host}:${port}${endpoint}`;
    try {
      client = mqtt.connect(connectUrl, options);
      this._client = client;
    } catch (error) {
      // console.log('mqtt.connect error', error)
      this._client.end();
    }
    client.on('connect', () => {
      // console.log('Connection succeeded!')
      this.checkWSNum = 1;
      this.messageService.showToastMessage('Connection succeeded!', 'success');
    });
    client.on('error', error => {
      // console.log('Connection failed', error)
      this.checkWSNum = 0;
      this.messageService.showToastMessage('Connection failed!', 'error');
      this._client.end();
    });
    client.on('message', (topic, message) => {
      console.log(`Received message ${message} from topic ${topic}`);
    });
  
  }

点击一次:

点击第二次,会不断触发创建连接:

 

 原因:

存在两个客户端 clientId 相同,一直争同一连接,导致一直重连.

扫描二维码关注公众号,回复: 15943383 查看本文章

解决方案一(建议):

点击测试按钮后置灰, 鼠标悬浮测试按钮时,提示clienID刷新.对clienId内容刷新后再允许点击.

方案二:

测试按钮点击连接测试成功后,关闭mqtt.对于我这个来说不建议,因为在其他地方还需要订阅主题.

猜你喜欢

转载自blog.csdn.net/wdm891026/article/details/127769859