登录
首页 >  Golang >  Go问答

无法与 MQTT 服务器建立连接

来源:stackoverflow

时间:2024-02-28 15:24:25 284浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《无法与 MQTT 服务器建立连接》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

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

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="网络错误:拨号 tcp:缺少地址"。

我可以做什么来解决这个问题?


正确答案


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

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

因此 tcp://address:port 似乎是该映射中不存在的某个相应值的关键,导致 broker 变量很可能被设置为空字符串。 为了进行调试,您可能需要使用调试器查看 broker 变量的值,或者在设置 broker 后添加 fmt.Printf("'%s'\n", Broker) 语句。该变量很可能为空,导致输出 ''

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

到这里,我们也就讲完了《无法与 MQTT 服务器建立连接》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>