package test import ( "fmt" "testing" MQTT "github.com/eclipse/paho.mqtt.golang" "myschools.me/suguo/snippet/mosquitto" ) func TestSubscribe(t *testing.T) { mosquitto.Init(&mosquitto.Config{}) if err := mosquitto.Subscribe(connHandler, connLostHandler); err != nil { t.Fatal(err) } topic := "xtj/aaaa" payload := []byte("sadfdsaf") mosquitto.Distribute(&topic, 0, false, &payload) select {} } var connHandler MQTT.OnConnectHandler = func(client MQTT.Client) { token := client.Subscribe("#", 0, serviceHandler) if token.Wait() && token.Error() != nil { fmt.Println(token.Error()) } } var connLostHandler MQTT.ConnectionLostHandler = func(client MQTT.Client, err error) { fmt.Println(err.Error()) } //具体业务订阅的处理,此处为示例 var serviceHandler MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) { fmt.Println(msg.Topic()) }