作者:赵子昊122510 | 来源:互联网 | 2023-06-13 08:36
前言:
首先安装EMQTT服务器,参考上一篇
本文测试方法:
使用Go语言调用客户端(paho.mqtt.golang)API向EMQTT服务器发消息
测试步骤:
1、下载客户端库
https://github.com/eclipse/paho.mqtt.golang
2、测试代码
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/eclipse/paho.mqtt.golang"
)
//set callback function
var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("TOPIC: %sn", msg.Topic())
fmt.Printf("MSG: %sn", msg.Payload())
}
func main() {
mqtt.DEBUG = log.New(os.Stdout, "", 0)
mqtt.ERROR = log.New(os.Stdout, "", 0)
//connect mqtt-server and set clientID
opts := mqtt.NewClientOptions().AddBroker("tcp://localhost:1883").SetClientID("mqtt_client")
//set userName
opts.SetUsername("mqtt_test")
opts.SetKeepAlive(2 * time.Second)
opts.SetDefaultPublishHandler(f)
opts.SetPingTimeout(1 * time.Second)
//create object
c := mqtt.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
//subscribe topic
if token := c.Subscribe("go-mqtt/sample", 0, nil); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
//publish topic
for i := 0; i <5; i++ {
text := fmt.Sprintf("this is msg #%d!", i)
token := c.Publish("go-mqtt/sample", 0, false, text)
token.Wait()
}
//unsubscribe topic
time.Sleep(6 * time.Second)
if token := c.Unsubscribe("go-mqtt/sample"); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
c.Disconnect(250)
time.Sleep(1 * time.Second)
}
3、服务器查看消息接受情况