【发布时间】: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()接受字符串类型。