dscs63759 2019-05-08 10:19
浏览 319

保持MQTT Go客户端运行

I think it is a silly question, I need a MQTT Client to keep running after connection and subscription. I never encountered the problem because my MQTT clients are always coupled with an HTTP server, and when launching a HTTP server, the code don't stop running.

But in the present use case I only need a MQTT Client to subscribe to some topic and stay alive.

Here is what I do (the function just connect to a broker and subcribe to one topic.)

func main() {
    godotenv.Load("./.env")
    _initMqttConnection()
}

I need the client to stay connected and not stop just after the subscription is done.

How to perform that simple thing ?

Edit 1 : Complete Code

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "os"
    "path/filepath"
    "strings"

    "github.com/yosssi/gmq/mqtt"
    "github.com/yosssi/gmq/mqtt/client"

    "github.com/joho/godotenv"

    "github.com/skratchdot/open-golang/open"
)

var cli *client.Client

func _initMqttConnection() {
    cli = client.New(&client.Options{
        ErrorHandler: func(err error) {
            fmt.Println(err)
        },
    })
    defer cli.Terminate()
    log.Println("Connecting to " + os.Getenv("mqtt_host"))

    err := cli.Connect(&client.ConnectOptions{
        Network:  "tcp",
        Address:  os.Getenv("mqtt_host"),
        UserName: []byte(os.Getenv("mqtt_user")),
        Password: []byte(os.Getenv("mqtt_password")),
        ClientID: []byte("mqtt_video_launcher"),
    })
    if err != nil {
        log.Println("Error 1")
        panic(err)
    }
    log.Println("Connected to MQTT")

    topic_to_sub := []byte("/" + os.Getenv("video_topic"))

    err = cli.Subscribe(&client.SubscribeOptions{
        SubReqs: []*client.SubReq{
            &client.SubReq{
                TopicFilter: topic_to_sub,
                QoS:         mqtt.QoS0,
                Handler: func(topicName, message []byte) {
                    //do struff with message
          fmt.Println(string(topicName), string(message))
                },
            },
        },
    })
    if err != nil {
        panic(err)
    }
    log.Println("Subscription OK : " + string(topic_to_sub[:len(topic_to_sub)]))
}

func main() {
    godotenv.Load("./.env")
    _initMqttConnection()
}

The temporary solution I use is adding :

http.ListenAndServe(":", nil)

at the end.

</div>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 微信公众号自制会员卡没有收款渠道啊
    • ¥15 stable diffusion
    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿