51 lines
1.2 KiB
Go
51 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
emitter "github.com/emitter-io/go"
|
|
"time"
|
|
)
|
|
|
|
func main() {
|
|
// Create the options with default values
|
|
o := emitter.NewClientOptions()
|
|
o.AddBroker("tcp://localhost:1883")
|
|
o.SetClientID("go-emitter-subscribe")
|
|
|
|
// Set the message handler
|
|
o.SetOnMessageHandler(func(client emitter.Emitter, msg emitter.Message) {
|
|
fmt.Printf("Received message from %s: %s\n", msg.Topic(), msg.Payload())
|
|
})
|
|
|
|
o.SetOnConnectionLostHandler(func(client emitter.Emitter, err error) {
|
|
fmt.Printf("Lost connection to broker: %s\n", err.Error())
|
|
for {
|
|
cToken := client.Connect()
|
|
if cToken.Wait() && cToken.Error() != nil {
|
|
time.Sleep(5 * time.Second)
|
|
} else {
|
|
setupSubscribe(client)
|
|
break
|
|
}
|
|
}
|
|
})
|
|
|
|
c := emitter.NewClient(o)
|
|
sToken := c.Connect()
|
|
if sToken.Wait() && sToken.Error() != nil {
|
|
panic("Error on Client.Connect(): " + sToken.Error().Error())
|
|
}
|
|
|
|
setupSubscribe(c)
|
|
|
|
time.Sleep(600* time.Second)
|
|
}
|
|
|
|
func setupSubscribe(client emitter.Emitter) {
|
|
sToken := client.Subscribe("CockozbDw5Bu3EKTJEfaJIBbj1OVGH5P", "test/")
|
|
|
|
if sToken.Wait() && sToken.Error() != nil {
|
|
panic("Error on Subscribe: " + sToken.Error().Error())
|
|
}
|
|
}
|
|
|