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 SQL数据库操作问题
  • ¥100 关于lm339比较电路出现的问题
  • ¥15 Matlab安装yalmip和cplex功能安装失败
  • ¥15 加装宝马安卓中控改变开机画面
  • ¥15 STK安装问题问问大家,这种情况应该怎么办
  • ¥15 关于罗技鼠标宏lua文件的问题
  • ¥15 halcon ocr mlp 识别问题
  • ¥15 已知曲线满足正余弦函数,根据其峰值,还原出整条曲线
  • ¥20 无法创建新的堆栈防护界面
  • ¥15 sessionStorage在vue中的用法