drqvr26084 2017-05-03 11:58 采纳率: 100%
浏览 1587
已采纳

如何检查我与mqtt代理的连接是否断开?

我正在尝试使用paho pkg来通过golang构建MQTT子客户端,当代理断开连接时,我的客户端就会出现问题,我一开始以为会出现丢失的消息,但这种情况并没有发生,启动代理后,MQTT子客户端却无法获得由MQTT PUB客户端发送的消息。

为什么会发生这种事,我怎么才能解决呢?

代码:

package main

import (
    "fmt"
    "os"

    mqtt "github.com/eclipse/paho.mqtt.golang"
)

var (
    broker                     = "tcp://localhost:1883"
    f      mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
        fmt.Printf("TOPIC: %s
", msg.Topic())
        fmt.Printf("MSG: %s
", msg.Payload())
    }
)

func main() {
    //create a ClientOptions
    opts := mqtt.NewClientOptions().AddBroker(broker)
    opts.SetClientID("group-one")
    opts.SetDefaultPublishHandler(f)

    //create and start a client using the above ClientOptions
    c := mqtt.NewClient(opts)
    if token := c.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
    }

    if token := c.Subscribe("test", 0, nil); token.Wait() && token.Error() != nil {
        fmt.Println(token.Error())
        os.Exit(1)
    }

    for {

    }
}
  • 写回答

1条回答 默认 最新

  • dongxi1879 2017-05-03 14:25
    关注

    Assign a custom OnConnectionLostHandler to catch connection lost event, so you can perform additional action whenever the client loses connection. If you set the AutoReconnect option to true (which is the default behavior), the client will automatically reconnects to the broker after connection lost. Please note that after connection lost, your subscription state/info may not being saved by the broker, so you won't be able to receive any message. To deal with this issue, move topic subscription to OnConnect handler. Below is an example implementation:

    package main
    
    import (
        "fmt"
        "os"
        "time"
    
        mqtt "github.com/eclipse/paho.mqtt.golang"
    )
    
    func messageHandler(c mqtt.Client, msg mqtt.Message) {
        fmt.Printf("TOPIC: %s
    ", msg.Topic())
        fmt.Printf("MSG: %s
    ", msg.Payload())
    }
    
    func connLostHandler(c mqtt.Client, err error) {
        fmt.Printf("Connection lost, reason: %v
    ", err)
    
        //Perform additional action...
    }
    
    func main() {
        //create a ClientOptions
        opts := mqtt.NewClientOptions().
            AddBroker("tcp://localhost:1883").
            SetClientID("group-one").
            SetDefaultPublishHandler(messageHandler).
            SetConnectionLostHandler(connLostHandler)
    
        //set OnConnect handler as anonymous function
        //after connected, subscribe to topic
        opts.OnConnect = func(c mqtt.Client) {
            fmt.Printf("Client connected, subscribing to: test/topic
    ")
    
            //Subscribe here, otherwise after connection lost, 
            //you may not receive any message
            if token := c.Subscribe("test/topic", 0, nil); token.Wait() && token.Error() != nil {
                fmt.Println(token.Error())
                os.Exit(1)
            }
        }
    
        //create and start a client using the above ClientOptions
        c := mqtt.NewClient(opts)
        if token := c.Connect(); token.Wait() && token.Error() != nil {
            panic(token.Error())
        }
    
        for {
            //Lazy...
            time.Sleep(500 * time.Millisecond)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器