MQTT_Client实例Golang代码

杜曜灿
2023-12-01

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

 类似资料: