美文网首页
Go MQTT Example

Go MQTT Example

作者: 霡霂976447044 | 来源:发表于2020-04-19 22:21 被阅读0次

main.go
doc: http://godoc.org/github.com/eclipse/paho.mqtt.golang

package main

import (
    "fmt"
    gomqtt "github.com/eclipse/paho.mqtt.golang"
    "sync"
)

func main() {
    // 1、创建Client
    // 2. 连接MQTT
    sw := sync.WaitGroup{}
    opts := gomqtt.NewClientOptions().AddBroker("localhost:1883")
    client := gomqtt.NewClient(opts)
    if token := client.Connect(); token.Wait() && token.Error() != nil {
        fmt.Println(token.Error())
    }
    client.Publish("test", 0, false, "hello")
    client.Subscribe("test", 0, func(client gomqtt.Client, message gomqtt.Message) {
        msg := string(message.Payload())
        fmt.Println(msg)
        if msg == "exit"{
            sw.Done()
        }
    })
    defer client.Disconnect(1000)
    sw.Add(1)
    sw.Wait()
}

相关文章

网友评论

      本文标题:Go MQTT Example

      本文链接:https://www.haomeiwen.com/subject/zuswbhtx.html