duan1989643 2018-06-28 19:30
浏览 156

使用Goroutine订阅MQTT不打印消息

I currently have Go code that subscribes to a topic and prints out sensor data. The part that prints out the sensor data is in a Goroutine, however, nothing is printing out currently. This is my code:

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
", 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
")
    }
    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

}

I'm wondering if it has to do with the way I coded the sync.WaitGroup? Any ideas are appreciated.

  • 写回答

1条回答 默认 最新

  • dsj8086 2018-06-28 21:09
    关注

    I managed to fix it Here is my new code:

    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
    ", msg.Payload())
        }()
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog