0

I am trying to initiate a simple codebase to test MQTTNet's library implementation of its subscriber & publisher code using the local mosquito broker, and subsequently, through HiveMQ's WebSocket.

For now, these codes are within a C# Console Application from this tutorial, https://www.youtube.com/watch?v=lcsnsj1yBs0&ab_channel=RishabhSharma:

Publisher Code

static async Task Main(string[] args)
{
    Console.WriteLine("Publisher");
    var mqttFactory = new MqttFactory();
    IMqttClient mqttClient = mqttFactory.CreateMqttClient();
    var mqttClientOptions = new MqttClientOptionsBuilder()
                            .WithClientId(Guid.NewGuid().ToString())
                            .WithTcpServer("test.mosquito.org", 1883)
                            //.WithWebSocketServer("broker.hivemq.com:8000/mqtt")
                            .WithCleanSession()
                            .Build();

    mqttClient.UseConnectedHandler(e =>
    {
        Console.WriteLine("Connected to the Broker Succesfully");
    });

    mqttClient.UseDisconnectedHandler(e =>
    {
        Console.WriteLine("Disconnected to the Broker Succesfully");
    });

   await mqttClient.ConnectAsync(mqttClientOptions);

    Console.WriteLine("Press a key to publish the message");
    Console.ReadLine();

    await PublishMessageAsyn(mqttClient);

    await mqttClient.DisconnectAsync();
}
private static async Task PublishMessageAsyn(IMqttClient mqttClient)
{
    string messagePayload = "Hello!";
    var publishMessage = new MqttApplicationMessageBuilder()
                        .WithTopic("astar/vfarmproject")
                        .WithPayload(messagePayload)
                        .WithAtLeastOnceQoS()
                        .Build();
    if (mqttClient.IsConnected)
    {
        await mqttClient.PublishAsync(messagePayload);
        Console.WriteLine($"Published Message - {messagePayload}");
    }
}

Subscriber Code

static async Task Main(string[] args)
{
    Console.WriteLine("Subscriber");
    var mqttFactory = new MqttFactory();
    IMqttClient mqttClient = mqttFactory.CreateMqttClient();
    var mqttClientOptions = new MqttClientOptionsBuilder()
                            .WithClientId(Guid.NewGuid().ToString())
                            .WithTcpServer("test.mosquito.org", 1883)
                            //.WithWebSocketServer("broker.hivemq.com:8000/mqtt")
                            .WithCleanSession()
                            .Build();

    mqttClient.UseConnectedHandler(async e =>
    {
        Console.WriteLine("Connected to the Broker Succesfully");
        var topicFilter = new TopicFilterBuilder()
                            .WithTopic("astar/vfarmproject")
                            .Build();
        await mqttClient.SubscribeAsync(topicFilter);
    });

    mqttClient.UseDisconnectedHandler(e =>
    {
        Console.WriteLine("Disconnected to the Broker Succesfully");
    });

    mqttClient.UseApplicationMessageReceivedHandler(e =>
    {
        Console.WriteLine($"Received Message - {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
    });

    await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);

    Console.ReadLine();

    await mqttClient.DisconnectAsync();
}

The exception is thrown when trying to execute await mqttClient.ConnectAsync(mqttClientOptions); with the following stack trace:

Exception thrown: 'MQTTnet.Exceptions.MqttCommunicationTimedOutException' in System.Private.CoreLib.dll
An exception of type 'MQTTnet.Exceptions.MqttCommunicationTimedOutException' occurred in System.Private.CoreLib.dll but was not handled in user code
Ajax
  • 33
  • 5
  • Adding an extra "t" is likely to help - `test.mosquito.org` to `test.mosquitto.org`... – Brits Feb 24 '22 at 18:58
  • Hey @Brits, thanks for your suggestion. Unfortunately, it still doesn't work :( – Ajax Feb 25 '22 at 01:33
  • With the same error or something different? (you were trying to connect to a server that does not run an MQTT broker; fixing this should change things somewhat). Note that you will [probably have to](https://github.com/dotnet/MQTTnet/issues/1290) add a keepalive setting for this to work (e.g. `.WithKeepAlivePeriod(TimeSpan.FromSeconds(60))`). – Brits Feb 25 '22 at 01:55
  • Hey @Brits, yup same error, even with the KeepAlive setting, it doesn't seem to work with WebSocket, i.e., `.WithWebSocketServer("broker.hivemq.com:8000/mqtt")` either. – Ajax Feb 25 '22 at 07:14
  • I have successfully run your Subscriber (and verified that it receives messages using `test.mosquitto.org`). My version was pretty much a copy/paste with very minor changes to run as a [console app](https://aka.ms/new-console-template) - [code here](https://dotnetfiddle.net/PBSZR7). As such it looks like the issue may be something not specified in your question (sorry but I'm not watching the whole video :-) ). – Brits Feb 25 '22 at 22:52
  • Hmm... are you perhaps aware of how to handle `MqttCommunicationTimedOutException` in `System.Private.CoreLib.dll` as mentioned in the Stack Track. – Ajax Feb 28 '22 at 01:06
  • I'd guess it's a network issue so you could retry. Sorry I don't use .net much so can't really offer any other suggestions (my initial comment was mainly due to the issue being seethingly obvious). – Brits Feb 28 '22 at 01:15
  • @Brits Ah I see... thanks tho! Just to check, is there any way/MQTT setting we can implement to ensure the connection can be established properly to the MQTT broker? As some Wi-Fi seems to block the connection (presumably due to Firewall, etc)? – Ajax Mar 04 '22 at 02:21
  • I'd suggest using TLS and port 443 (as [aws](https://docs.aws.amazon.com/iot/latest/developerguide/protocols.html#protocol-port-mapping) and others do - that is least likely to be blocked). If the connection fails your only real option is to retry. – Brits Mar 04 '22 at 03:16

0 Answers0