vue中mqtt连接失败

我需要一直获取某个消息,来及时更新页面

我在安装了mqtt(4.1.0)后,相关使用代码如下:

import mqtt from 'mqtt'
//省略部分代码
created(){
  this.initMqtt('wh01/+');
}
initMqtt(topic){
    const _this = this;
    const cfg = Object.assign(mqttConfig, {
      username: 'mqtt_wh01_c',
      password: 'wh01c@123',
    });
    console.log('订阅配置: ', cfg, topic);
    _this.MQTT = mqtt.connect('ws://xxx/mqtt', cfg)
    _this.MQTT.on('error', (e) => {
      console.log('错误: ', e);
      _this.MQTT.end();
    });
    _this.MQTT.on('connect', (e) => {
      if(!e){
        // 订阅一个主题
        _this.MQTT.subscribe(topic, { qos: 1 }, (error) => {
          if (!error) {
            console.log(topic+' ---- 订阅成功')
          }else{
            console.log('订阅失败')
          }
        })
      }else console.log('s链接失败:', e);
    });
  },

始终报错:

image.png

用了个在线测试网站同样配置是能够收到消息的:
image.png

到底是哪里的问题?

阅读 6.5k
1 个回答

这里的问题

_this.MQTT.on('connect', (e) => {
      if(!e){
        // 订阅一个主题
        _this.MQTT.subscribe(topic, { qos: 1 }, (error) => {
          if (!error) {
            console.log(topic+' ---- 订阅成功')
          }else{
            console.log('订阅失败')
          }
        })
      }else console.log('s链接失败:', e);
    });

参考官方使用例子:

client.on('connect', function () {
  client.subscribe('presence', function (err) {
    if (!err) {
      client.publish('presence', 'Hello mqtt')
    }
  })
})

大家应该看出了,connec的回调事件是没有错误信息的(我代码中的e),回调参数的参数e其实是一个Packet对象,链接成功与否不应该根据这个判断,最后去掉if语句即可

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题