订阅完成之前,AWS MQTT连接丢失

时间:2018-02-16 17:38:57

标签: go mqtt iot aws-iot

我尝试连接到AWS MQTT时出现间歇性问题。有时它工作正常,其他时候没那么多。当我连接时,我收到此错误: 订阅完成前连接丢失

我真的不确定为什么会这样做,起初一切似乎都运转良好但现在却经常抛出这个错误。这是我用来连接的代码:

type ServerConnection struct {
    Cert     tls.Certificate
    Host     string
    Port     int
    Path     string
    Topic    string
    Qos      int
    Messages chan MQTT.Message
    Control  chan os.Signal
 }

func (server *ServerConnection) Start() error {
    cid := uuid.New().String()

    connOpts := &MQTT.ClientOptions{
            ClientID:             cid,
            CleanSession:         true,
            AutoReconnect:        true,
            MaxReconnectInterval: 1 * time.Second,
            KeepAlive:            30000,
            TLSConfig:            tls.Config{Certificates: []tls.Certificate{server.Cert}},
    }
    connOpts.SetConnectTimeout(30 * time.Second)
    connOpts.SetDefaultPublishHandler(func(client MQTT.Client, msg MQTT.Message) {
            server.Messages <- msg
    })
    brokerURL := fmt.Sprintf("tcps://%s:%d%s", server.Host, server.Port, server.Path)
    connOpts.AddBroker(brokerURL)
    mqttClient := MQTT.NewClient(connOpts)
    if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
            return token.Error()
    }
    // Subscribe
    go func() {
            log.Printf("subscribing")
            if token := mqttClient.Subscribe(server.Topic, byte(server.Qos), nil); token.Wait() && token.Error() != nil {
                    fmt.Println(token.Error())
                    os.Exit(1)
            }
            log.Printf("subscribed")

    }()
    server.ProcessMessages()
    log.Println("[MQTT] Connected")
    quit := make(chan struct{})
    signal.Notify(server.Control, os.Interrupt)
    go func() {
            <-server.Control
            mqttClient.Disconnect(250)
            fmt.Println("[MQTT] Disconnect")
            quit <- struct{}{}
    }()
    <-quit

    return nil

   }

1 个答案:

答案 0 :(得分:0)

基本上你需要将subscribe methid调用放在onConnectHandler中,这样可以确保在成功连接时调用subscribe(并重新连接) 处理程序在客户机选项中定义。