golang mqtt发布并订阅 [英] golang mqtt publish and subscribe

查看:1812
本文介绍了golang mqtt发布并订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道我在哪里可以得到在无限循环中同时发布和订阅的示例MQTT客户端Go(golang)代码吗?

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

我正在与在MacO上运行的Mosquitto经纪人进行通讯.

I am messaging with a Mosquitto broker running on MacOs.

更多细节...

  1. 获取来自网络的消息(主题)
  2. 根据该消息计算内容
  3. 将计算结果发送回网络(主题)

这是我正在使用的代码:

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\n", 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

我在GoDocs中浏览了一些有关如何保持连接打开的提示,但似乎没有任何意义.我当然可以做一个无限循环 超过订阅",但这似乎效率低下.

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.

推荐答案

我在GoDocs中浏览了一些有关如何保持连接打开的提示,但似乎没有任何意义.我当然可以对订阅"进行无限循环,但这似乎效率很低.

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.

好的.在找到了解决方案. https://github.com/eclipse/paho .mqtt.golang/blob/master/cmd/stdoutsub/main.go . 本质上,我必须打开一个订阅频道. 这是新代码:

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

这篇关于golang mqtt发布并订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆