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

如何检查我与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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵