当前位置:   article > 正文

mqtt的简单实现(golang)_golang 正则表达式 mqtt topic

golang 正则表达式 mqtt topic
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. MQTT "github.com/eclipse/paho.mqtt.golang"
  6. )
  7. var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
  8. //fmt.Printf("topic: %s\n", msg.Topic())
  9. fmt.Printf("date: %s\n", msg.Payload())
  10. }
  11. type Client struct {
  12. MQTT.Client
  13. Url string
  14. }
  15. func SetMqtt(url string) *Client {
  16. c := &Client{
  17. Url: url,
  18. }
  19. c.initMqtt()
  20. return c
  21. }
  22. func (m *Client) initMqtt() {
  23. opts := MQTT.NewClientOptions()
  24. opts.AddBroker(m.Url)
  25. m.Client = MQTT.NewClient(opts)
  26. }
  27. func (m *Client) Conn() {
  28. fmt.Println("conn")
  29. token := m.Client.Connect()
  30. if token.Wait() && token.Error() != nil {
  31. fmt.Println(token.Error())
  32. }
  33. }
  34. func (m *Client) DisConn() {
  35. fmt.Println("disconn")
  36. m.Client.Disconnect(250)
  37. }
  38. func (m *Client) Sub() {
  39. fmt.Println("sub")
  40. token := m.Client.Subscribe("date", 0, f)
  41. if token.Wait() && token.Error() != nil {
  42. fmt.Println(token.Error())
  43. }
  44. }
  45. func (m *Client) Pub() {
  46. fmt.Println("pub")
  47. s := time.Now().String()
  48. token := m.Client.Publish("date", 0, false, s)
  49. if token.Wait() && token.Error() != nil {
  50. fmt.Println(token.Error())
  51. }
  52. }
  53. func main() {
  54. c := SetMqtt("tcp://broker.mqttdashboard.com:1883")
  55. c.Conn()
  56. c.Sub()
  57. c.Pub()
  58. time.Sleep(time.Second)
  59. c.DisConn()
  60. }

 

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

闽ICP备14008679号