pub_test.go 749 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package main
  2. import (
  3. "fmt"
  4. "testing"
  5. "time"
  6. "github.com/eclipse/paho.mqtt.golang"
  7. )
  8. func TestPub(t *testing.T) {
  9. opts := mqtt.NewClientOptions()
  10. opts.AddBroker("tcp://39.98.34.197:1883")
  11. opts.SetClientID("test")
  12. opts.SetUsername("sg1")
  13. opts.SetPassword("dashoopwd")
  14. // opts.SetDefaultPublishHandler(messageHandler)
  15. opts.SetKeepAlive(2 * time.Second)
  16. opts.SetPingTimeout(1 * time.Second)
  17. c := mqtt.NewClient(opts)
  18. if token := c.Connect(); token.Wait() && token.Error() != nil {
  19. panic(token.Error())
  20. }
  21. for i := 0; i < 3; i++ {
  22. text := fmt.Sprintf("this is msg #%d!", i)
  23. token := c.Publish("go-mqtt/sample", 0, false, text)
  24. token.Wait()
  25. }
  26. time.Sleep(6 * time.Second)
  27. c.Disconnect(250)
  28. time.Sleep(1 * time.Second)
  29. }