I am using Go v1.17.2 on Linux to connect to AWS MQTT using the paho.mqtt.golang library v1.4.1. I am basing my code on this sample from EMQX using TLS with the certificates provided by AWS IOT Core.
When I run the publish and subscribe code in the same go program as per the above example from EMQX everything works and I can see the following output:
2022/08/11 19:47:42 Connected
Subscribed to topic: topic_1
2022/08/12 13:47:42 Received message: Message 0 from topic: topic_1
2022/08/11 19:47:43 Received message: Message 1 from topic: topic_1
...
2022/08/11 19:47:51 Received message: Message 9 from topic: topic_1
However, if I run the publish code in one go program (using go run) and run the subscribe in a separate program on the same machine at the same time, then the subscribe fails on each message with an EOF error:
2022/08/11 19:54:50 Connected
2022/08/11 19:54:54 Connect lost: EOF
...
2022/08/11 19:54:59 Connected
2022/08/11 19:54:59 Connect lost: EOF
Here is the publish code
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Fatalln(token.Error())
}
publish(client, *topic)
client.Disconnect(250)
...
func publish(client mqtt.Client, topic string) {
num := 10
for i := 0; i < num; i++ {
text := fmt.Sprintf("Message %d", i)
token := client.Publish(topic, 0, false, text)
token.Wait()
time.Sleep(time.Second)
}
}
and the subscribe code
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
log.Fatalln(token.Error())
}
sub(client, *topic)
time.Sleep(11 * time.Second)
client.Disconnect(250)
...
func sub(client mqtt.Client, topic string) {
token := client.Subscribe(topic, 1, nil)
token.Wait()
log.Printf("Subscribed to topic: %s", topic)
}
If I run the subscribe code only, and use the AWS IOT console to publish some message that also works
2022/08/11 20:25:27 Connected
2022/08/11 20:25:27 Subscribed to topic: topic_1
2022/08/11 20:25:29 Received message: {
"message": "Hello from AWS IoT console"
} from topic: topic_1
2022/08/11 20:25:30 Received message: {
"message": "Hello from AWS IoT console"
} from topic: topic_1
It looks like the issue is to do with having two connections open to AWS IOT/MQTT at the same time.
Here is my MQTT client options config
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tls://%s:%d", *host, 8883))
opts.SetClientID("basicPubSub")
opts.SetTLSConfig(tlsConfig)
opts.SetDefaultPublishHandler(messagePubHandler)
opts.OnConnect = connectHandler
opts.OnConnectionLost = connectLostHandler