mqtt.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "time"
  6. mqtt "github.com/eclipse/paho.mqtt.golang"
  7. )
  8. const (
  9. //broker = "tcp://rabbitmq.irdi.eu:1883" // change to your broker's IP/hostname
  10. broker = "tcp://localhost:2222" // change to your broker's IP/hostname
  11. topic = "test/topic"
  12. clientID = "go-mqtt-client"
  13. )
  14. func main() {
  15. // Message handler for received messages
  16. messagePubHandler := func(client mqtt.Client, msg mqtt.Message) {
  17. fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
  18. }
  19. // MQTT connection options
  20. opts := mqtt.NewClientOptions()
  21. opts.AddBroker(broker)
  22. opts.SetClientID(clientID)
  23. opts.OnConnect = func(c mqtt.Client) {
  24. fmt.Println("Connected to broker")
  25. }
  26. opts.OnConnectionLost = func(c mqtt.Client, err error) {
  27. fmt.Printf("Connection lost: %v\n", err)
  28. }
  29. opts.SetDefaultPublishHandler(messagePubHandler)
  30. fmt.Println("Connecting to broker ...")
  31. // Connect to the broker
  32. client := mqtt.NewClient(opts)
  33. if token := client.Connect(); token.Wait() && token.Error() != nil {
  34. fmt.Printf("Error connecting to broker: %v\n", token.Error())
  35. os.Exit(1)
  36. }
  37. // Subscribe to a topic
  38. if token := client.Subscribe(topic, 1, nil); token.Wait() && token.Error() != nil {
  39. fmt.Printf("Subscribe error: %v\n", token.Error())
  40. os.Exit(1)
  41. }
  42. // Publish a message
  43. text := "Hello from Go!"
  44. token := client.Publish(topic, 0, false, text)
  45. token.Wait()
  46. // Wait to receive message
  47. time.Sleep(5 * time.Second)
  48. // Disconnect
  49. client.Disconnect(250)
  50. fmt.Println("Disconnected")
  51. }
  52. // go run mqtt.go