| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- package main
- import (
- "fmt"
- "os"
- "time"
- mqtt "github.com/eclipse/paho.mqtt.golang"
- )
- const (
- //broker = "tcp://rabbitmq.irdi.eu:1883" // change to your broker's IP/hostname
- broker = "tcp://localhost:2222" // change to your broker's IP/hostname
- topic = "test/topic"
- clientID = "go-mqtt-client"
- )
- func main() {
- // Message handler for received messages
- messagePubHandler := func(client mqtt.Client, msg mqtt.Message) {
- fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
- }
- // MQTT connection options
- opts := mqtt.NewClientOptions()
- opts.AddBroker(broker)
- opts.SetClientID(clientID)
- opts.OnConnect = func(c mqtt.Client) {
- fmt.Println("Connected to broker")
- }
- opts.OnConnectionLost = func(c mqtt.Client, err error) {
- fmt.Printf("Connection lost: %v\n", err)
- }
- opts.SetDefaultPublishHandler(messagePubHandler)
- fmt.Println("Connecting to broker ...")
- // Connect to the broker
- client := mqtt.NewClient(opts)
- if token := client.Connect(); token.Wait() && token.Error() != nil {
- fmt.Printf("Error connecting to broker: %v\n", token.Error())
- os.Exit(1)
- }
- // Subscribe to a topic
- if token := client.Subscribe(topic, 1, nil); token.Wait() && token.Error() != nil {
- fmt.Printf("Subscribe error: %v\n", token.Error())
- os.Exit(1)
- }
- // Publish a message
- text := "Hello from Go!"
- token := client.Publish(topic, 0, false, text)
- token.Wait()
- // Wait to receive message
- time.Sleep(5 * time.Second)
- // Disconnect
- client.Disconnect(250)
- fmt.Println("Disconnected")
- }
- // go run mqtt.go
|