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

如何检查我与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 arm虚拟机无法和物理机互通
    • ¥15 如何在此代码上增加一个统计学生生源的功能?(语言-c语言)
    • ¥15 Android导航条遮盖异常
    • ¥15 计算机网络技术基础问题
    • ¥15 设置mac系统只能访问指定网站
    • ¥15 西门子博途 s7 1200控制三台步进电机
    • ¥15 基于非参数的方向距离函数求污染物影子价格(有偿)
    • ¥15 vue+element 生成table