Golang Paho MQTT over Websocket



嘿,我试图通过Golang Paho MQTT客户端连接到AWS IoT Core。我尝试了正常的MQTT连接,没有问题。接下来,我想通过Websocket上的MQTT尝试连接,但在Paho中找不到任何相关的内容。Mqtt文档。我如何使Websocket连接?如果有必要,我可以从正常的MQTT连接发布代码。编辑,这是我的代码:

package main
import (
"crypto/tls"
"fmt"
"time"
MQTT "github.com/eclipse/paho.mqtt.golang"
)
type Message struct {
message string
}
/*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() {
cer, err := tls.LoadX509KeyPair("cd5a04e9fd9a094326c9ee0cdc1e1f7b2e3510a9e106968683d333a2a4344ca7-certificate.pem.crt",
"./cd5a04e9fd9a094326c9ee0cdc1e1f7b2e3510a9e106968683d333a2a4344ca7-private.pem.key")
check(err)
cid := "ClientID"
// AutoReconnect option is true by default
// CleanSession option is true by default
// KeepAlive option is 30 seconds by default
connOpts := MQTT.NewClientOptions() // This line is different, we use the constructor function instead of creating the instance ourselves.
connOpts.SetClientID(cid)
connOpts.SetMaxReconnectInterval(1 * time.Second)
connOpts.SetTLSConfig(&tls.Config{Certificates: []tls.Certificate{cer}})
host := "a2to6mbspmaw82-ats.iot.eu-west-1.amazonaws.com"
port := 443
brokerURL := fmt.Sprintf("wss://%s:%d", host, port)
connOpts.AddBroker(brokerURL)
mqttClient := MQTT.NewClient(connOpts)
if token := mqttClient.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
var message = "message from lap"
for message != "bye" {
token := mqttClient.Publish("some_topic", 0, false, message)
token.Wait()
message = "bye"
}
}
func check(err error) {
if err != nil {
panic(err)
}
}

来自Eclipse Paho GoLang页面

所需的连接类型由方案指定ClientOptions结构中的连接URL设置,例如:

  • tcp://mqtt.eclipseprojects.io:1883-使用普通TCP连接到端口1883上的mqtt. eclipseprojectsio
  • ws://mqtt.eclipseprojects.io:1883-使用WebSockets在端口1883连接mqtt.eclipseprojects.io
  • tls://mqtt.eclipseprojects.io:8883-连接到mqtt.eclipseprojects.io端口8883使用TLS (ssl://和tcp://是tls的同义词://)

列表中的第二个条目建议您使用正确的模式(ws://wss://)传入URL

相关内容

  • 没有找到相关文章

最新更新