我有一个蚊子经纪人,它在防火墙后面的服务器上运行。所需的端口是开放的,从外部,我检查它是否正在使用:
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库对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()
我也尝试过对QOS进行查核,但是结果是相似的。我遗漏了什么?
https://stackoverflow.com/questions/68578819
复制相似问题