I am using a MQTT broker credentials to connect with the MQTT broker but my code always goes to the disconnected block of code. After that it shows me a error message like un-handling exception. I was done lots of research on this topic but i can't find a suitable solution for this issue.
Here is my complete C# code for MQTT broker connection,
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Extensions.ManagedClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TreonConsole
{
class Program
{
private static IMqttClient _Client;
private static IMqttClientOptions _options;
static void Main(string[] args)
{
try
{
Console.WriteLine("Starting Subscriber...");
//Create subscriber client
var factory = new MqttFactory();
_Client = factory.CreateMqttClient();
string clientid= Guid.NewGuid().ToString();
//Configure options
_options = new MqttClientOptionsBuilder()
.WithClientId(clientid)
.WithTcpServer("b925270106984f21be3ae9d1d48b400fh.s112.eu.hivemq.cloud", 8883)
.WithCredentials("iap", "Iap321?")
.WithCleanSession()
.Build();
//Handlers
_Client.UseConnectedHandler(e =>
{
Console.WriteLine("Connected successfully with MQTT Brokers.");
//Subscribe to topic
_Client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("test").Build()).Wait();
});
_Client.UseDisconnectedHandler(e =>
{
Console.WriteLine("Disconnected from MQTT Brokers.");
});
_Client.UseApplicationMessageReceivedHandler(e =>
{
Console.WriteLine("Received Application Messages");
Console.WriteLine($"+Topic={e.ApplicationMessage.Topic}");
Console.WriteLine($"+Payload={Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
Console.WriteLine($"+Qos={e.ApplicationMessage.QualityOfServiceLevel}");
Console.WriteLine($"Retaain={e.ApplicationMessage.Retain}");
Console.WriteLine();
});
//actaully connect
_Client.ConnectAsync(_options).Wait();
Console.WriteLine("Press Key to Exit");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
}