我无法通过websockets连接到任何MQTT经纪人。
我首先设置了一个启用了websockets的本地代理。连接未建立。然后,我尝试连接到一些也不起作用的公共经纪人。 你能给我一个解决这个问题的提示吗? 可能只是防火墙问题。
package main
import (
"fmt"
"sync"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
func main() {
var ipRange []string
ipRange = append(ipRange,
"tcp://mqtt.flespi.io:1883",
"tcp://test.mosquitto.org:1883",
"tcp://iot.eclipse.org:1883",
"tcp://mqtt.fluux.io:1883",
"tcp://broker.hivemq.com:1883",
"ws://mqtt.flespi.io:80",
"ws://iot.eclipse.org:80",
"ws://broker.hivemq.com:8000",
"ws://test.mosquitto.org:80",
"ws://broker.bevywise.com:8443",
"ws://mqtt.dioty.co:8080",
)
opts := mqtt.NewClientOptions()
opts.ConnectTimeout = 1 * time.Second
opts.PingTimeout = 1 * time.Second
opts.WriteTimeout = 1 * time.Second
var clients []mqtt.Client
for i := 0; i < len(ipRange); i++ {
opt := *opts
opt.AddBroker(ipRange[i])
clients = append(clients, mqtt.NewClient(&opt))
}
startTime := time.Now()
var validBrokers []string
var wg sync.WaitGroup
wg.Add(len(clients))
fmt.Println("--- discovery started (", len(clients), "clients) ---")
for i := 0; i < len(clients); i++ {
go connectMQTT(clients[i], &wg, &validBrokers)
}
wg.Wait()
fmt.Println("--- discovery finished ---")
fmt.Println("\nvalid brokers after", time.Now().Sub(startTime), ":")
for i := 0; i < len(validBrokers); i++ {
fmt.Println(validBrokers[i])
}
}
func connectMQTT(client mqtt.Client, waitgroup *sync.WaitGroup, brokers *[]string) {
defer waitgroup.Done()
bla := client.OptionsReader()
if token := client.Connect(); token.Wait() {
fmt.Println(bla.Servers()[0].Hostname()+":"+bla.Servers()[0].Port(), client.IsConnected())
if token.Error() == nil {
*brokers = append(*brokers, bla.Servers()[0].Hostname()+":"+bla.Servers()[0].Port())
}
}
}