![](/style/images/good.png)
1
![](/style/images/bad.png)
【笔记】Go 语言实现 MQTT
source link: https://loli.fj.cn/zh-CN/2023/12/24/Go%E8%AF%AD%E8%A8%80%E5%AE%9E%E7%8E%B0MQTT/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Go 语言实现 MQTT
go get github.com/eclipse/paho.mqtt.golang
127.0.0.1
:指定 MQTT 服务器 IP 地址1883
:指定 MQTT 服务器端口号
var options = mqtt.NewClientOptions()
options.AddBroker(fmt.Sprintf("tcp://127.0.0.1:1883"))
var client = mqtt.NewClient(options)
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Panicln(token.Error())
}
指定用户名密码
<username>
:用户名<password>:密码
options.SetUsername("<username>")
options.SetPassword("<passwordd>")
指定连接 ID
options.SetClientID("go-mqtt-client")
配置过滤器
options.SetDefaultPublishHandler(func(client mqtt.Client, message mqtt.Message) {
fmt.Println(message.Payload(), message.Topic())
})
连接建立完成事件
options.OnConnect = func(client mqtt.Client) {
fmt.Println("Connected")
}
连接断开事件
options.OnConnectionLost = func(client mqtt.Client, err error) {
fmt.Printf("Connect Lost: %v", err)
}
topic/test
:订阅的主题
var token = client.Subscribe("topic/test", 1, nil)
token.Wait()
topic/test
:发布的主题<str>
:发布的信息内容
var token = client.Publish("topic/test", 0, false, string("<str>"))
token.Wait()
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK