当前位置:   article > 正文

MQTT_Client实例Golang代码_go 创建mqttclient数组

go 创建mqttclient数组

MQTT短连接


package test

import (
	"fmt"
	"time"
	MQTT "github.com/eclipse/paho.mqtt.golang"
	LOG "github.com/sirupsen/logrus"
)


func main() {
	opts := MQTT.NewClientOptions()
	opts.AddBroker("tcp://127.0.0.1:1883")
	opts.SetClientID("custom-store")

	var callback MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
	}

	c := MQTT.NewClient(opts)
	if token := c.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	LOG.Info("create mqtt client")

	c.Subscribe("/go-mqtt/sample", 0, callback)
	LOG.Info("subscibe topic /go-mqtt/sample")
	for i := 0; i < 10; i++ {
		text := fmt.Sprintf("this is msg #%d!", i)
		token := c.Publish("/go-mqtt/sample", 1, false, text)
		token.Wait()
	}

	for i := 1; i < 10; i++ {
		time.Sleep(1 * time.Second)
	}
	c.Disconnect(250)
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/42890
推荐阅读
相关标签
  

闽ICP备14008679号