doukui9491 2018-02-16 17:38
浏览 314

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

I'm having an intermittent issue with go trying to connect to AWS MQTT. Sometimes it works fine, other times not so much. When I connect I get this error: Connection lost before Subscribe completed

I'm really not sure why it does this, at first everything seemed to work fine but now it throws this error more often than not. Here's the code that I'm using to connect:

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条回答

  • dpf5207 2018-05-18 16:10
    关注

    Basically you need to put the subscribe methid call inside the onConnectHandler, this will make sure that the subscribe is being called upon successful connection (and reconnect) The handler is defined in the client options.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog