我正在探索 mosquitto 作为一个完整的初学者。我有一个 golang 测试程序,我正在使用它来查看它是如何管理消息的,但是该程序的后续运行显示收到了额外的消息。
import (
mqtt "github.com/eclipse/paho.mqtt.golang"
log "github.com/sirupsen/logrus"
"strconv"
"time"
)
var sent int
var received int
func Test() {
sent = 0
received = 0
const TOPIC = "mytopic/test"
opts := mqtt.NewClientOptions().AddBroker("tcp://localhost:1883").SetClientID("client1").SetResumeSubs(false).SetAutoReconnect(false).SetCleanSession(true)
client1 := mqtt.NewClient(opts)
if token := client1.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
if token := client1.Subscribe(TOPIC, 2, receiver1); token.Wait() && token.Error() != nil {
panic(token.Error())
}
defer howManySent()
defer howManyReceived()
defer client1.Disconnect(1)
for index:=0;index<3;index++ {
sendMsg := "client1 message " + strconv.Itoa(index)
if token := client1.Publish(TOPIC, 2, true, sendMsg); token.Wait() && token.Error() != nil {
panic(token.Error())
} else {
sent++
}
time.Sleep(1 * time.Second)
}
time.Sleep(1*time.Second)
}
func howManyReceived() {
log.Warn("RECEIVED:", received)
}
func howManySent() {
log.Warn("SENT:", sent)
}
func receiver1(client mqtt.Client, msg mqtt.Message) {
received++
msg.Ack()
output := "message id:" + strconv.Itoa(int(msg.MessageID())) + " message = " + string(msg.Payload())
log.Warn(output)
}
第一次运行的输出:
WARN[0000] message id:1 message = client1 message 0
WARN[0001] message id:2 message = client1 message 1
WARN[0002] message id:3 message = client1 message 2
WARN[0004] RECEIVED:3
WARN[0004] SENT:3
我究竟做错了什么?
白衣非少年
相关分类