question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Problems with QoS > 0

See original GitHub issue

Describe your question

Hi, i recently created 2 c# application with the MqttNet nuget. All works perfectly, but I have some problems with the redelivery of the QoS 1 and 2 messages not delivered (client offline).

My client connection code is like this:

`static async void StartClient() { //private System.Diagnostics.EventLog Log;

        //IsoftMQTTClient settings = new IsoftMQTTClient();
        //settings.LoadSettings();
        //StartServer();
        EventLog Log1 = new EventLog();

        if (!EventLog.SourceExists("IsMQTTClient"))
            EventLog.CreateEventSource("IsMQTTClient", "IsMQTTClient");

        Log1.Source = "IsMQTTClient";
        Log1.Log = "IsMQTTClient";
        


        try {
            // Create a new MQTT client.
            var factory = new MqttFactory();
            var mqttClient = factory.CreateMqttClient();


            MqttClientOptions options;

            //Log1.WriteEntry("aaa " + GlobalVar.MQTT_CLIENT_CLEAN_SESSION.ToUpper());

            if (GlobalVar.MQTT_CLIENT_CLEAN_SESSION.ToUpper() == "S")
            {
                // Create TCP based options using the builder.
                options = (MqttClientOptions)new MqttClientOptionsBuilder()
                    .WithClientId(GlobalVar.MQTT_CLIENT_CLIENT_ID_WINDOWS_SERVICE)
                    .WithTcpServer(GlobalVar.MQTT_BROKER_HOST, Int32.Parse((GlobalVar.MQTT_BROKER_PORT))) // Port is optional
                    .WithCredentials(GlobalVar.MQTT_BROKER_USERNAME, GlobalVar.MQTT_BROKER_PASSWORD)
                    .WithCommunicationTimeout(new TimeSpan(0, 1, 0))
                    //.WithTls()
                    .WithCleanSession()
                    .Build();
            }
            else
            {
                options = (MqttClientOptions)new MqttClientOptionsBuilder()
                    .WithClientId(GlobalVar.MQTT_CLIENT_CLIENT_ID_WINDOWS_SERVICE)
                    .WithTcpServer(GlobalVar.MQTT_BROKER_HOST, Int32.Parse((GlobalVar.MQTT_BROKER_PORT))) // Port is optional
                    .WithCredentials(GlobalVar.MQTT_BROKER_USERNAME, GlobalVar.MQTT_BROKER_PASSWORD)
                    .WithCommunicationTimeout(new TimeSpan(0, 1, 0))
                    .WithCleanSession(false)
                    //.WithTls()
                    .Build();
            }

            //Log1.WriteEntry(options.CleanSession.ToString());

            await mqttClient.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken
            Log1.WriteEntry("### CONNECTED TO BROKER ###");
            //await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("#").Build());
            //Log1.WriteEntry("### SUBSCRIBED TO ALL TOPICS ###");
            SubscribeToTopics(GlobalVar.MQTT_CLIENT_TOPIC_SUBSCRIPTION, mqttClient, options);
            //while (true)
            //{
            await PoolMessagesAsync(mqttClient, options);
            //}


            //Console.ReadKey();
        } catch (Exception ex) { Log1.WriteEntry("Errore: " + ex.ToString()); }
        }`

inside SubscribeToTopics() i’m subscribing to all topics available, and while client is connected i recive every message the broker recives await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("#").Build()); Log1.WriteEntry("### SUBSCRIBED TO ALL TOPICS ###");

My Broker is hosted like this: `static async void StartServer() { var factory = new MqttFactory();

        // Configure MQTT server.
        var optionsBuilder = new MqttServerOptionsBuilder()
            .WithConnectionValidator(c =>
            {
                if (c.ClientId.Length < 1)
                {
                    c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
                    return;
                }

                System.Diagnostics.EventLog Log1;

                Log1 = new EventLog();

                if (!EventLog.SourceExists("IsMQTTBroker"))
                    EventLog.CreateEventSource("IsMQTTBroker", "IsMQTTBroker");

                Log1.Source = "IsMQTTBroker";
                Log1.Log = "IsMQTTBroker";

                //Log1.WriteEntry(GlobalVar.MQTT_BROKER_HOST);
                //Log1.WriteEntry(GlobalVar.MQTT_BROKER_PORT);
                //Log1.WriteEntry(GlobalVar.MQTT_BROKER_USERNAME);
                //Log1.WriteEntry(GlobalVar.MQTT_BROKER_PASSWORD);
                //Log1.WriteEntry(GlobalVar.MQTT_CLIENT_CLIENT_ID_WINDOWS_SERVICE);
                //
                //Log1.WriteEntry("c Username " +c.Username);
                //Log1.WriteEntry("c Password " + c.Password);
                //Log1.WriteEntry("Int32.Parse((GlobalVar.MQTT_BROKER_PORT)) " + Int32.Parse((GlobalVar.MQTT_BROKER_PORT)).ToString());


                if (c.Username != GlobalVar.MQTT_BROKER_USERNAME)
                {
                    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    return;
                }

                if (c.Password != GlobalVar.MQTT_BROKER_PASSWORD)
                {
                    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                    return;
                }

                c.ReasonCode = MqttConnectReasonCode.Success;
            })
            .WithConnectionBacklog(100)
            .WithDefaultEndpointPort(Int32.Parse((GlobalVar.MQTT_BROKER_PORT)))
            .WithPersistentSessions();

        var mqttServer = new MqttFactory().CreateMqttServer();
        await mqttServer.StartAsync(optionsBuilder.Build());

        Console.WriteLine("Press any key to exit.");
        Console.ReadLine();
        //await mqttServer.StopAsync();
    }`

when i stop my client, send some messages with QoS 1 or 2 and start my client again those messages are vanished. I have a static and unique ClientID, and the client is always started with “.WithCleanSession(false)”. Any idea on what i’m missing to manage those messages recived while offline?

Thanks

Best regards, Andrea

Which project is your question related to?

  • Client
  • Server

Issue Analytics

  • State:open
  • Created 3 years ago
  • Comments:8

github_iconTop GitHub Comments

1reaction
davemcdermidcommented, Feb 12, 2021

Sorry I can’t help further, I’m really not an expert here. I found http://mqtt-explorer.com/ useful for visualising what was happening, and Wireshark for digging into what was really being sent & received. Not sure if that’s helpful for you.

0reactions
dkavickicommented, Oct 19, 2022

fwiw I had the same issue until I did .WithSessionExpiryInterval(9999) Then it worked for me. (with the ManagedClient) However, I’ve noticed that my test Mqttnet server would send the message every time (and not just once) whenever I start and connect the client again

Read more comments on GitHub >

github_iconTop Results From Across the Web

What's the problem of always using QoS 0 in a MQTT ...
Here's my questions: Apart from the broker and client crashes, Are there any other reasons for a QoS 0 message to not arrive...
Read more >
Problems with QoS > 0 · Issue #1089 · dotnet/MQTTnet
Hi, i recently created 2 c# application with the MqttNet nuget. All works perfectly, but I have some problems with the redelivery of...
Read more >
What is MQTT Quality of Service (QoS) 0,1, & 2?
This means that the recipient does not acknowledge receiving the message, and the sender does not store or re-transmit it.
Read more >
Introduction to MQTT QoS 0, 1, 2 - EMQ
The main disadvantage of QoS 0 is that messages may be lost, depending on the network conditions. This means that you may miss...
Read more >
Troubleshoot Network Quality of Service (QoS)
First, the network may be experiencing generalized issues, such as saturated bandwidth, high latency or packet loss, that are affecting all traffic.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found