使用Goroutine订阅MQTT不打印消息

时间:2018-06-28 19:30:34

标签: go mqtt goroutine

我目前拥有可以订阅主题并打印出传感器数据的Go代码。打印传感器数据的部分位于 Goroutine 中,但是目前没有任何内容可打印。这是我的代码:

package main

import (
    "fmt"
    MQTT "github.com/eclipse/paho.mqtt.golang"
    "os"
    "os/signal"
    "syscall"
    "sync"
)



var wg sync.WaitGroup

func subscriber(client MQTT.Client, message MQTT.Message) {
    wg.Add(1)
    go func() {
        defer wg.Done()
        fmt.Printf("%s\n", message.Payload())
    }()
}

func main() {

    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)

    opts := MQTT.NewClientOptions().AddBroker("tcp://test.mosquitto.org:1883")

    //opts.SetDefaultPublishHandler(f)
    // Topic to subscribe to for sensor data
    topic := "sensor/data"
    client := MQTT.NewClient(opts)
    if token := client.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
    } else {
        fmt.Printf("Connected to server\n")
    }
    opts.OnConnect = func(c MQTT.Client) {
        //if token := c.Subscribe(topic, 0, f); token.Wait() && token.Error() != nil {
        if token := c.Subscribe(topic, 0, subscriber); token.Wait() && token.Error() != nil {

            panic(token.Error())

        }
    }

    wg.Wait()

    <-c

}

我想知道是否与我编写sync.WaitGroup的方式有关?任何想法表示赞赏。

1 个答案:

答案 0 :(得分:0)

我设法解决了这是我的新代码:

var wg sync.WaitGroup
// All messages are handled here - printing published messages and publishing new messages
var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {

wg.Add(1)
    go func() {
        defer wg.Done()
        fmt.Printf("%s\n", msg.Payload())
    }()

}
相关问题