main.go
doc: http://godoc.org/github.com/eclipse/paho.mqtt.golang
package main
import (
"fmt"
gomqtt "github.com/eclipse/paho.mqtt.golang"
"sync"
)
func main() {
// 1、创建Client
// 2. 连接MQTT
sw := sync.WaitGroup{}
opts := gomqtt.NewClientOptions().AddBroker("localhost:1883")
client := gomqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
}
client.Publish("test", 0, false, "hello")
client.Subscribe("test", 0, func(client gomqtt.Client, message gomqtt.Message) {
msg := string(message.Payload())
fmt.Println(msg)
if msg == "exit"{
sw.Done()
}
})
defer client.Disconnect(1000)
sw.Add(1)
sw.Wait()
}
网友评论