You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用paho.mqtt.golang连接AWS IoT Core Websocket失败求助

使用MQTT + Websocket + AWS IoT + paho.mqtt.golang连接发布消息时遇到协议不支持错误

我尝试实现一个基于MQTT + Websocket + AWS IoT + paho.mqtt.golang的最简连接及消息发布示例,但执行时出现错误。以下是我的代码、运行输出及相关配置说明:

代码实现

package main

import (
    "crypto/tls"
    "crypto/x509"
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "time"

    MQTT "github.com/eclipse/paho.mqtt.golang"
)

func main() {
    MQTT.ERROR = log.New(os.Stdout, "[ERROR] ", 0)
    MQTT.CRITICAL = log.New(os.Stdout, "[CRIT] ", 0)
    MQTT.WARN = log.New(os.Stdout, "[WARN]  ", 0)
    MQTT.DEBUG = log.New(os.Stdout, "[DEBUG] ", 0)

    topic := flag.String("topic", "", "The topic name to/from which to publish/subscribe")
    broker := flag.String("broker", "tcp://iot.eclipse.org:1883", "The broker URI. ex: tcp://10.10.1.1:1883")
    user := flag.String("user", "", "The User (optional)")
    id := flag.String("id", "testgoid", "The ClientID (optional)")
    payload := flag.String("message", "", "The message text to publish (default empty)")
    flag.Parse()

    fmt.Printf("Sample Info:\n")
    fmt.Printf("\tbroker:    %s\n", *broker)
    fmt.Printf("\tclientid:  %s\n", *id)
    fmt.Printf("\tuser:      %s\n", *user)
    fmt.Printf("\ttopic:     %s\n", *topic)
    fmt.Printf("\tmessage:   %s\n", *payload)

    // Load client certificates
    cert, err := tls.LoadX509KeyPair("./iot-certificate.pem.crt", "./iot-private.pem.key")
    if err != nil {
        panic(err)
    }

    // Load CA certificates
    caCert, err := ioutil.ReadFile("./AmazonRootCA1.pem")
    if err != nil {
        panic(err)
    }
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    tlsConfig := &tls.Config{
        Certificates: []tls.Certificate{cert},
        RootCAs:      caCertPool,
        ClientAuth:   tls.NoClientCert,
        ClientCAs:    nil,
        MinVersion:   tls.VersionTLS13,
        // ALPN and SNI extensions specified by AWS IoT docs
        NextProtos: []string{"mqtt"},
        ServerName: "{ID}.iot.{REGION}.amazonaws.com",
    }

    opts := MQTT.NewClientOptions()
    opts.AddBroker(*broker)
    opts.SetClientID(*id).SetTLSConfig(tlsConfig)
    opts.SetUsername(*user)
    opts.SetMaxReconnectInterval(10 * time.Second)

    client := MQTT.NewClient(opts)
    if token := client.Connect(); token.Wait() && token.Error() != nil {
        panic(token.Error())
    }
    fmt.Println("Sample Publisher Started")
    fmt.Println("---- doing publish ----")
    token := client.Publish(*topic, byte(0), false, *payload)
    token.Wait()
    client.Disconnect(250)
    fmt.Println("Sample Publisher Disconnected")
}

运行输出

Sample Info:
        broker:    wss://{ID}.iot.{REGION}.amazonaws.com/mqtt
        clientid:  test
        user:      ?x-amz-customauthorizer-name=IoTAuthorizer
        topic:     test
        message:   hello, world
[DEBUG] [client]   Connect()
[DEBUG] [store]    memorystore initialized
[DEBUG] [client]   about to write new connect msg
[ERROR] [client]   websocket: protocol "mqtt" was given but is not supported;sharing tls.Config with net/http Transport can cause this error: unexpected EOF
[WARN]  [client]   failed to connect to broker, trying next
[ERROR] [client]   Failed to connect to a broker
[DEBUG] [store]    memorystore closed
panic: network Error : websocket: protocol "mqtt" was given but is not supported;sharing tls.Config with net/http Transport can cause this error: unexpected EOF

相关配置说明

  • 使用名为IoTAuthorizer的自定义授权器,仅返回默认策略,未启用身份验证
  • TLS证书从AWS IoT控制台「Security > Certificates」生成,证书状态为「Active」并已绑定对应策略
  • 授权器已关闭令牌验证

内容的提问来源于stack exchange,提问作者Cameron Toy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 06:00:00