【问题标题】:Subscribing MQTT using Goroutine not printing messages使用 Goroutine 订阅 MQTT 不打印消息
【发布时间】:2018-12-07 23:04:01
【问题描述】:

我目前有订阅主题并打印传感器数据的 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 的方式有关?任何想法表示赞赏。

【问题讨论】:

  • 我相信您需要向您的 goroutine 发送消息才能使其正常工作。 go func(msg MQTT.Message) { fmt.Println(msg.Payload) }(message)
  • @Fishdigger 这似乎不起作用。 message 已经作为参数传递给函数。

标签: go mqtt goroutine


【解决方案1】:

我设法修复它这是我的新代码:

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多