dotnet / MQTTnet

MQTTnet is a high performance .NET library for MQTT based communication. It provides a MQTT client and a MQTT server (broker). The implementation is based on the documentation from http://mqtt.org/.
MIT License
4.44k stars 1.06k forks source link

NullReferenceException on ConnectAsync #907

Closed mridah closed 4 years ago

mridah commented 4 years ago

Describe your question

I tried using the sample code provided with .NET framework, but I keep getting System.NullReferenceException on ConnectAsync()

image

Which project is your question related to?

This is my code:

MqttFactory factory = new MqttFactory();
MqttClient client;

public Form1()
{
    InitializeComponent();
    ConnectAsync();
}

public async Task ConnectAsync()
{
    client = (MqttClient)factory.CreateMqttClient();
    // I even tried using var client = factory.CreateMqttClient();
    // but got the same Error
    // though i need the variable to be global

    var options = new MqttClientOptionsBuilder()
        .WithClientId("Client1")
        .WithTcpServer("http://192.168.0.115", 1883)
        .WithCleanSession()
        .Build();

    await client.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken

    client.UseDisconnectedHandler(async e =>
    {
        Console.WriteLine("### DISCONNECTED FROM SERVER ###");
        await Task.Delay(TimeSpan.FromSeconds(5));
        try
        {
            await client.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken
        }
        catch
        {
            Console.WriteLine("### RECONNECTING FAILED ###");
        }
    });

    client.UseApplicationMessageReceivedHandler(e =>
    {
        Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
        Task.Run(() => client.PublishAsync("/indiadel"));
    });

    client.UseConnectedHandler(async e =>
    {
        Console.WriteLine("### CONNECTED WITH SERVER ###");

        // Subscribe to a topic
        await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("/indiadel").Build());

        Console.WriteLine("### SUBSCRIBED ###");

        //await PublishMessage("/indiadel", "hello world !#");
    });

}

Am I doing something wrong ??? @chkr1011

chkr1011 commented 4 years ago

Hi, first of all your TCP server is wrong. It will not work with the prefix "http://" in it. I was not able to reproduce the issue with netstandard and regular .net framework.

But I got this exception on UWP. Are you building an UWP application?

mridah commented 4 years ago

@chkr1011 hi, no I'm working on normal .NET Framework 4.7.2. Not using UWP.

I'm getting the same error even after removing the protocol prefix. Any other suggestion ?

chkr1011 commented 4 years ago

Please show me the output. I can see a little bit from it in the screenshot but is is cut off. It seems that another exception is thrown before the null ref exception happens.

Apart from that I have fixed this issue in latest master branch.

mridah commented 4 years ago

Hi @chkr1011 thanks for the fast reply. I checked it again. It's not throwing any error but it's just not connecting to the broker.

Please see the working on this Link

chkr1011 commented 4 years ago

I am wondering if this can work at all. You have the connect method with a Task but you do not await it. Please try with .Wait() on the returning task. Apart from that it looks good to me.

mridah commented 4 years ago

Hey,

I changed the connection code from await client.ConnectAsync(options, CancellationToken.None); to client.ConnectAsync(options, CancellationToken.None); and it started working.

Maybe the handlers require the connection to be established beforehand.

chkr1011 commented 4 years ago

No sorry I mean the call in your constructor. Not the connect method.

eifinger commented 4 years ago

I have the same problem when I supply a wrong server address. I have the Mqttclient as a IHostedService in an ASP.NET app running dotnetcore3.1

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            try
            {
                await this.mqttClient.ConnectAsync(this.mqttClientOptions, cancellationToken);
            }
            catch (MqttCommunicationException e)
            {
                this.logger.LogWarning("Could not connect to MQTT Broker", e);
            }
        }

I get an NullReferenceException (which I cannot catch) when I use the debugger. The warning is logged. As I said I tried to add another catch (Exception e) to catch the NullRefence but this never logged anything.

chkr1011 commented 4 years ago

Please try 3.0.10-rc1. The issue is fixed in that version.

eifinger commented 4 years ago

Can confirm that the issue is fixed for me. Thank you!