【问题标题】:Unable to connect to the MQTT broker无法连接到 MQTT 代理
【发布时间】:2021-06-16 12:37:55
【问题描述】:

我写了以下代码来订阅一个主题

func run(c *cli.Context) error {
    customFormatter := new(log.TextFormatter)
    customFormatter.TimestampFormat = time.StampMilli
    customFormatter.FullTimestamp = true
    log.SetFormatter(customFormatter)
    log.Info("begin running")
    username := c.String("xxxxxxxxx")
    password := c.String("xxxxxxxxx")
    broker := c.String("tcp://address:port")
    clientID := newRandClientID()
    opts := MQTT.NewClientOptions()
    opts.SetClientID(clientID)
    opts.AddBroker(broker)
    opts.SetUsername(username)
    opts.SetPassword(password)
    opts.SetOnConnectHandler(onConnected)
    opts.SetConnectionLostHandler(onConnectionLost)
    tlsconfig, err := newTLSConfig()
    if err == nil {
        opts.SetTLSConfig(tlsconfig)
    }
    client := MQTT.NewClient(opts)
    if token := client.Connect(); token.Wait() && token.Error() != nil {
        log.WithField("MQTT", token.Error()).Info("failed to connect MQTT broker")
    }
    defer client.Disconnect(250)

    sigChan := make(chan os.Signal)
    exitChan := make(chan struct{})
    signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
    log.WithField("signal", <-sigChan).Info("signal received")
    go func() {
        log.Warning("stopping wlora")
        exitChan <- struct{}{}
    }()
    select {
    case <-exitChan:
    case s := <-sigChan:
        log.WithField("signal", s).Info("signal received, stopping immediately")
    }
    return nil
}

当我运行它时,我收到以下错误:

level=info msg="连接 MQTT 代理失败" MQTT="网络错误: dial tcp: missing address"。

我能做些什么来解决这个问题?

【问题讨论】:

  • broker 设置为什么? (您通过c.String 设置此功能,但不提供此功能,因此不清楚您最终使用的是什么值)。如果您提供minimal, reproducible example,将更容易提供帮助;如果您不想显示地址,则可以使用tcp://test.mosquitto.org:1883
  • 你的c.String()函数是做什么的?您将c 作为cli.Context 类型传入,但您没有显示该类型是/做什么。 opts.AddBroker() 接受字符串类型。

标签: go mqtt paho


【解决方案1】:

您的 func (c *cli.Context) c.String(key string) string 函数似乎访问了上下文提供的地图。

上面的函数签名是一个猜测,因为它没有提供。

所以tcp://address:port 似乎是该映射中不存在的某个对应值的键,导致很可能将broker 变量设置为空字符串。 为了调试,您可能希望使用调试器查看broker 变量的值,或者在设置broker 之后添加fmt.Printf("'%s'\n", broker) 语句。该变量很可能为空,从而导致输出 ''

尽管如此,正如 cmets 所提到的,尚不清楚 c.String(...) 函数的作用。

【讨论】: