2026年3月24日火曜日

golangで公開ブローカへpub成功

package main import ( "fmt" "time" mqtt "github.com/eclipse/paho.mqtt.golang" ) func main() { // 1. MQTTブローカーの設定 broker := "tcp://broker.hivemq.com:1883" // 公開ブローカー topic := "fseigojp/test" // smart-appで受信できた clientID := "go_client_pub" // 名前はなんでもよかった opts := mqtt.NewClientOptions() opts.AddBroker(broker) opts.SetClientID(clientID) // 接続ロスト時のハンドラ(オプション) opts.OnConnectionLost = func(c mqtt.Client, err error) { fmt.Printf("Connection lost: %v\n", err) } // 2. クライアントの作成と接続 client := mqtt.NewClient(opts) if token := client.Connect(); token.Wait() && token.Error() != nil { panic(token.Error()) } fmt.Println("Connected to", broker) // 3. メッセージのパブリッシュ payload := fmt.Sprintf("Hello from Go! Time: %s", time.Now().Format(time.RFC3339)) token := client.Publish(topic, 1, false, payload) token.Wait() // 完了を待つ fmt.Printf("Published to %s: %s\n", topic, payload) // 4. クライアントの切断 client.Disconnect(250) fmt.Println("Disconnected") }

0 件のコメント:

コメントを投稿