可以通过 defer 关键字在函数结束时调用 mqtt.Disconnect() 方法来断开 mqtt 连接,例如:

import (
    "fmt"
    "github.com/eclipse/paho.mqtt.golang"
)

func myFunc() {
    // 创建 mqtt 客户端
    opts := mqtt.NewClientOptions().AddBroker("tcp://localhost:1883")
    client := mqtt.NewClient(opts)

    // 连接 mqtt 服务器
    if token := client.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
    }

    // 订阅主题
    if token := client.Subscribe("mytopic", 0, nil); token.Wait() && token.Error() != nil {
        panic(token.Error())
    }

    // 接收消息
    for {
        msg := <-client.C
        fmt.Printf("Received message: %s\n", msg.Payload())
    }

    // 断开 mqtt 连接
    defer client.Disconnect(250)
}

在函数结束时,defer 关键字会调用 client.Disconnect(250) 方法,将 mqtt 连接断开。

golang 函数中的mqtt连接,在主程序接收后断开 怎么设置

原文地址: https://www.cveoy.top/t/topic/rRx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录