I need an help, I can't connect with the broker. I'm using MQTTNet library into my api project .net core this is my code:
// GET: api/<SendCommandController>
[HttpGet]
public void Get()
{
var options = new MqttClientOptionsBuilder()
.WithTcpServer("broker.hivemq.com", 1883)
.Build();
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
mqttClient.ConnectAsync(options, CancellationToken.None);
var message = new MqttApplicationMessageBuilder()
.WithTopic("Test/Mqtt")
.WithPayload("Hello World")
.WithExactlyOnceQoS()
.WithRetainFlag()
.Build();
mqttClient.PublishAsync(message, CancellationToken.None);
}
so I follow the tutorial but can't connect to broker hivemq and I can't connect to my personal broker. So, I tested hivemq broker with mqtt.fx and works. Only in the code the return is connected = false.
Any ideas? the error is "the client is not connected"
C# is not a language I've done much with, but I assume you are missing an await
before mqttClient.ConnectAsync(options, CancellationToken.None);
so the rest of the code waits for the connection to complete before trying to send the message