gpt4 book ai didi

go - 无法使用Paho库连接到mosquitto 2.0

转载 作者:行者123 更新时间:2023-12-03 10:10:46 25 4
gpt4 key购买 nike

我似乎无法从paho库(“github.com/eclipse/paho.golang/paho”)的golang连接到mosquitto 2.0代理。谁能指出我的方式的错误?
我从paho chat example中获取了连接逻辑,并尝试连接到我的本地主机服务器,但是原因码为135(未授权)。然后,我尝试使用mosquitto_pub成功连接到mosquitto服务器。在两种情况下,我都使用相同的用户名和密码。 mosquitto日志输出如下:

1608068903: New connection from 127.0.0.1:58794 on port 1883.
1608068903: Client <unknown> disconnected, not authorised.
1608069349: New connection from 127.0.0.1:58908 on port 1883.
1608069349: New client connected from 127.0.0.1:58908 as test (p5, c1, k60, u'username').
我正在使用的mosquitto_pub命令是:
snap run mosquitto.pub -h localhost -t hello -u username -P password -m hello -V mqttv5 -i test
golang代码为:
import (
"context"
"fmt"
"github.com/eclipse/paho.golang/paho"
log "github.com/sirupsen/logrus"
"net"
)

func Test() {
conn, err := net.Dial("tcp", "localhost:1883")
if err != nil {
log.Fatalf("Failed to connect to %s: %s", "localhost", err)
}
c := paho.NewClient(paho.ClientConfig{
Router: paho.NewSingleHandlerRouter(func(m *paho.Publish) {
log.Printf("%s : %s", m.Properties.User["chatname"], string(m.Payload))
}),
Conn: conn,
})

username := "username"
password := "password"

cp := &paho.Connect{
KeepAlive: 30,
ClientID: "test",
CleanStart: false,
Username: username,
Password: []byte(password),
}
ca, err := c.Connect(context.Background(), cp)
if ca.ReasonCode != 0 {
log.Fatalf("Failed to connect to %s : %d - %s", "localhost", ca.ReasonCode, ca.Properties.ReasonString)
}
if err != nil {
log.Fatalln(err)
}

fmt.Printf("Connected to %s\n", "localhost")

}

最佳答案

UsernameFlagPasswordFlag添加到paho.Connect中,例如:

cp := &paho.Connect{
KeepAlive: 30,
ClientID: "test",
CleanStart: false,
Username: username,
UsernameFlag: true,
Password: []byte(password),
PasswordFlag: true,
}
paho.golang文档需要工作,但是 mqtt v5 spec对此进行了介绍。我已经用Mosquitto 2.0.1对此进行了测试并成功连接。

关于go - 无法使用Paho库连接到mosquitto 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65314401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com