dqed19166 2018-02-19 18:43
浏览 751
已采纳

golang mqtt发布并订阅

Does anybody know where I can get some example MQTT client Go (golang) code that does both publish and subscribe in an infinite loop ?

I am messaging with a Mosquitto broker running on MacOs.

In more detail...

  1. Get a message from the network (a topic)
  2. Compute something based on that message
  3. Send the result of the computation back to the network (topic)

Here is the code I am using:

package main

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

var knt int

var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) 
{ 
   fmt.Printf("MSG: %s
", msg.Payload())
   text:= fmt.Sprintf("this is result msg #%d!", knt)
   knt++
   token := client.Publish("nn/result", 0, false, text)
   token.Wait()
}

func main() {
   knt = 0

   opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883")
   opts.SetClientID("mac-go")
   opts.SetDefaultPublishHandler(f)

   c := MQTT.NewClient(opts)
   if token := c.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
   }

  if token := c.Subscribe("nn/sensors", 0, nil); token.Wait() && 
     token.Error() != nil {
     fmt.Println(token.Error())
     os.Exit(1)
  }

  time.Sleep(3 * time.Second)
} //end of main

I looked through the GoDocs for some hint as to how to keep the connections open but nothing seems pertinent. I can certainly do an infinite loop over the 'subscribe' but that seems inefficient.

  • 写回答

1条回答 默认 最新

  • duannima8347 2018-02-21 12:40
    关注

    I looked through the GoDocs for some hint as to how to keep the connections open but nothing seems pertinent. I can certainly do an infinite loop over the 'subscribe' but that seems inefficient.

    Ok. Found a solution at . https://github.com/eclipse/paho.mqtt.golang/blob/master/cmd/stdoutsub/main.go. Essentially, I had to open up a channel for the subscribe. Here is the new code:

    package main
    
    import (
        "fmt"
        MQTT "github.com/eclipse/paho.mqtt.golang"
        "os"
        "os/signal"
        "syscall"
    )
    
    var knt int
    var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
        fmt.Printf("MSG: %s
    ", msg.Payload())
        text := fmt.Sprintf("this is result msg #%d!", knt)
        knt++
        token := client.Publish("nn/result", 0, false, text)
        token.Wait()
    }
    
    func main() {
        knt = 0
        c := make(chan os.Signal, 1)
        signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    
        opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883")
        opts.SetClientID("mac-go")
        opts.SetDefaultPublishHandler(f)
        topic := "nn/sensors"
    
        opts.OnConnect = func(c MQTT.Client) {
                if token := c.Subscribe(topic, 0, f); token.Wait() && token.Error() != nil {
                        panic(token.Error())
                }
        }
        client := MQTT.NewClient(opts)
        if token := client.Connect(); token.Wait() && token.Error() != nil {
                panic(token.Error())
        } else {
                fmt.Printf("Connected to server
    ")
        }
        <-c
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于#flink#的问题:关于docker部署flink集成hadoop的yarn,请教个问题flink启动yarn-session.sh连不上hadoop
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题