Esempio di Client MQTT implementato in go tramite paho.mqtt.golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/eclipse/paho.mqtt.golang" | |
"log" | |
"os" | |
"os/signal" | |
"syscall" | |
) | |
const ( | |
brokAddr = "localhost" | |
port = 1883 | |
hostId = "Main" | |
topic = "test" | |
) | |
func receiveCallback(client mqtt.Client, message mqtt.Message) { | |
fmt.Printf("Topic: %v\tPayload: %s\n", message.Topic(), message.Payload()) | |
} | |
func main() { | |
quit := make(chan os.Signal) | |
signal.Notify(quit, os.Interrupt, syscall.SIGTERM) | |
opts := mqtt.NewClientOptions().AddBroker(fmt.Sprintf("tcp://%v:%v", brokAddr, port)) | |
opts.SetClientID(hostId) | |
client := mqtt.NewClient(opts) | |
connectionToken := client.Connect() | |
if connectionToken.Wait() && connectionToken.Error() != nil { | |
log.Fatal(connectionToken.Error()) | |
} | |
subscriptionToken := client.Subscribe(topic, 0, receiveCallback) | |
if subscriptionToken.Wait() && subscriptionToken.Error() != nil { | |
log.Fatal(subscriptionToken.Error()) | |
} | |
<-quit | |
client.Disconnect(200) | |
fmt.Println("Bye!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment