当前位置:   article > 正文

MQTT篇3---- MQTT发送数据与订阅主题_mqtt报文数据类型主题

mqtt报文数据类型主题

MQTT发送数据与订阅主题,go语言实现。

  1. package main
  2. import (
  3. "fmt"
  4. mqtt "github.com/eclipse/paho.mqtt.golang"
  5. "time"
  6. )
  7. var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
  8. fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
  9. }
  10. var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
  11. fmt.Println("Connected")
  12. }
  13. var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
  14. fmt.Printf("Connect lost: %v", err)
  15. }
  16. func main() {
  17. var broker = "172.16.3.119"
  18. var port = 1883
  19. opts := mqtt.NewClientOptions()
  20. opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
  21. opts.SetClientID("go_mqtt_client33")
  22. opts.SetUsername("emqx")
  23. opts.SetPassword("public")
  24. opts.SetDefaultPublishHandler(messagePubHandler)
  25. opts.OnConnect = connectHandler
  26. opts.OnConnectionLost = connectLostHandler
  27. client := mqtt.NewClient(opts)
  28. if token := client.Connect(); token.Wait() && token.Error() != nil {
  29. panic(token.Error())
  30. }
  31. // 开启另外一个线程协程去subsribe订阅
  32. go sub(client)
  33. publish(client)
  34. }
  35. func sub(client mqtt.Client) {
  36. topic := "topic/test"
  37. token := client.Subscribe(topic, 1, nil)
  38. token.Wait()
  39. fmt.Printf("Subscribed to topic %s", topic)
  40. }
  41. func publish(client mqtt.Client) {
  42. num := 100000
  43. for i := 0; i < num; i++ {
  44. text := fmt.Sprintf("message:{Temperature:101,Rh:%d}", i)
  45. token := client.Publish("topic/test", 0, false, text)
  46. token.Wait()
  47. time.Sleep(time.Second)
  48. }
  49. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/42888
推荐阅读
相关标签
  

闽ICP备14008679号