热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何检查我与mqtt代理的连接是否断开?》经验,为你挑选了1个好方法。



1> putu..:

分配一个自定义项OnConnectionLostHandler来捕获连接丢失事件,以便您可以在客户端断开连接时执行其他操作。如果将AutoReconnect选项设置为true(这是默认行为),则客户端将在连接断开后自动重新连接到代理。请注意,连接断开后,代理可能不会保存您的订阅状态/信息,因此您将无法收到任何消息。要解决此问题,请将主题订阅移至OnConnect处理程序。下面是一个示例实现:

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\n", msg.Topic())
    fmt.Printf("MSG: %s\n", msg.Payload())
}

func connLostHandler(c mqtt.Client, err error) {
    fmt.Printf("Connection lost, reason: %v\n", 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\n")

        //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)
    }
}


要查看该消息,您需要设置DEBUG处理程序,例如,在main函数的第一行中添加mqtt.DEBUG = log.New(os.Stderr,“ DEBUG”,log.Ltime)`。
推荐阅读
author-avatar
栋逼逼丶
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有