go - golang paho mqtt 丢弃消息
问题描述
我有一个在防火墙后面的服务器中运行的蚊子代理。所需的端口是开放的,我从外部检查它是否正在使用:
mosquitto_sub -h [ip address] -t "#" -u [username] -P [password] -v
mosquitto_pub -h [ip address] -t "topic" -u [username] -P [password] -m "hello"
我可以看到发布的消息。我想用一个小的go程序做同样的事情,代码如下:
package main
import (
"crypto/tls"
"fmt"
"time"
"strconv"
MQTT "github.com/eclipse/paho.mqtt.golang"
)
func messageHandler(c MQTT.Client, msg MQTT.Message) {
fmt.Printf("TOPIC: %s\n", msg.Topic())
fmt.Printf("MSG: %s\n", msg.Payload())
}
func connLostHandler(c MQTT.Client, err error) {
fmt.Printf("Connection lost, reason: %v\n", err)
}
func main() {
opts := MQTT.NewClientOptions()
skipVerify := true
opts.AddBroker("tcp://[ip]:1883")
opts.SetTLSConfig(&tls.Config{InsecureSkipVerify: skipVerify})
//opts.SetTLSConfig(&tls.Config{InsecureSkipVerify: skipVerify, ClientAuth: tls.NoClientCert})
opts.SetClientID("myclientid")
opts.SetAutoReconnect(true)
//opts.SetCleanSession(true)
opts.SetDefaultPublishHandler(messageHandler)
opts.SetConnectionLostHandler(connLostHandler)
opts.OnConnect = func(c MQTT.Client) {
fmt.Printf("Client connected\n")
}
client := MQTT.NewClient(opts)
token := client.Connect()
token.Wait()
fmt.Println("connected")
if token.Error() != nil {
fmt.Println("problems with connection")
panic(token.Error())
}
for i := 0; i < 10; i++ {
str := "hello: " + strconv.Itoa(i)
token := client.Publish("topic/temperature", 0, false, str)
token.Wait()
if token.Error() != nil {
fmt.Println("problems with pub")
}
fmt.Println("published")
time.Sleep(1000 * time.Millisecond)
}
fmt.Println("finished")
client.Disconnect(1)
}
我期望的结果是发布每个编号的 hello,但只有很少的消息通过。这是我的代理配置文件,我认为它具有使其工作的最低配置:
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example
log_dest file /var/log/mosquitto/mosquitto.log
log_type debug
allow_anonymous true
port 1883
listener 8883
我可以说我在使用 paho go 库时做错了,因为我已经使用 python paho mqtt 库使用 python 完成了一个类似的脚本,并且它运行良好:
import paho.mqtt.client as mqtt
import time
topic1 = "topic/temperature"
mqttClient = mqtt.Client()
mqttClient.connect([ip], 1883, 60)
mqttClient.loop_start()
for i in range(10000):
mqttClient.publish(topic1, "hello - " + str(i), qos= 0)
#time.sleep(1)
mqttClient.loop_stop()
mqttClient.disconnect()
我也尝试过 chaging QOS,但结果相似。我错过了什么?
解决方案
根据评论 - 问题是由于另一个客户使用相同的客户 ID。检查这一点的最简单方法是读取代理日志(从客户端的角度来看,连接只是在没有警告的情况下断开)。
MQTT 规范指出:
服务器必须处理从客户端发送的第二个 CONNECT 数据包作为协议违规并断开客户端 [MQTT-3.1.0-2]。有关处理错误的信息,请参阅第 4.8 节。
这是一个相当普遍的问题(并且是项目自述文件的常见问题部分中提到的第一件事)。
推荐阅读
- android - glGetAttribLocation 在我的一个属性上返回 -1
- ruby - 厨师/红宝石术语
- ios - 如何使用 7.3 将应用上传到应用商店
- c# - System.Web.HttpException:上传文件时超出最大请求长度> 3MB
- java - Scala-maven-plugin 无法执行
- javascript - 在 while 循环中使用 await 是一种不好的做法吗
- android - 浮动操作按钮未正确显示
- recursion - Prolog - 获取朋友的朋友列表
- visual-studio-code - VS Code 字符消失
- bash - 如何将输出值与各个变量相同