package main import ( "fmt" "testing" "time" "github.com/eclipse/paho.mqtt.golang" ) func TestPub(t *testing.T) { opts := mqtt.NewClientOptions() opts.AddBroker("tcp://39.98.34.197:1883") opts.SetClientID("test") opts.SetUsername("sg1") opts.SetPassword("dashoopwd") // opts.SetDefaultPublishHandler(messageHandler) opts.SetKeepAlive(2 * time.Second) opts.SetPingTimeout(1 * time.Second) c := mqtt.NewClient(opts) if token := c.Connect(); token.Wait() && token.Error() != nil { panic(token.Error()) } for i := 0; i < 3; i++ { text := fmt.Sprintf("this is msg #%d!", i) token := c.Publish("go-mqtt/sample", 0, false, text) token.Wait() } time.Sleep(6 * time.Second) c.Disconnect(250) time.Sleep(1 * time.Second) }