39 lines
877 B
Go
39 lines
877 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
MQTT "github.com/eclipse/paho.mqtt.golang"
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
|
|
fmt.Printf("TOPIC: %s (%s)\n", msg.Topic(), msg.MessageID())
|
|
fmt.Printf("MSG: %s\n", msg.Payload())
|
|
}
|
|
|
|
func main() {
|
|
opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883")
|
|
opts.SetClientID("go-simple")
|
|
opts.SetCleanSession(false)
|
|
opts.SetDefaultPublishHandler(f)
|
|
|
|
c := MQTT.NewClient(opts)
|
|
if token := c.Connect(); token.Wait() && token.Error() != nil {
|
|
panic(token.Error())
|
|
}
|
|
|
|
if token := c.Subscribe("test/#", 0, nil); token.Wait() && token.Error() != nil {
|
|
fmt.Println(token.Error())
|
|
os.Exit(1)
|
|
}
|
|
|
|
time.Sleep(300 * time.Second)
|
|
|
|
if token := c.Unsubscribe("go-mqtt/sample"); token.Wait() && token.Error() != nil {
|
|
fmt.Println(token.Error())
|
|
os.Exit(1)
|
|
}
|
|
|
|
c.Disconnect(250)
|
|
}
|