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 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器