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 |
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) } |
微信赞赏
支付宝赞赏