Code Monkey home page Code Monkey logo

Comments (3)

chkr1011 avatar chkr1011 commented on May 28, 2024

You must change a few things in order to get it running:

  1. You must use protocol version 5 which can be set in the client options builder
  2. Do not set ProcessPublish to false because then the message will basically treated as never sent
  3. You must use QoS 1 so that the client will receive a response. QoS 0 will not receive and response from the server
  4. When using protocol version 5 you must have a subscriber. Otherwise you will get a "NotMatchingSubscribers" response

from mqttnet.

grendo avatar grendo commented on May 28, 2024

I adjusted the unit test based on the guide above and it is now working

       [Test]
    public async Task TestCancelPublish()
    {
        var testTopic = "test/topic";
        var mqttFactory = new MqttFactory();
        var mqttServerOptions = new MqttServerOptionsBuilder()
            .WithDefaultEndpoint()
            .Build();
        using (var mqttServer = mqttFactory.CreateMqttServer(mqttServerOptions))
        {
            await mqttServer.StartAsync();
            bool messageInterceptedOnServer = false;
            
            mqttServer.InterceptingPublishAsync += async (args) =>
            {
                // intercept server message and set reason code to NotAuthorized
                args.Response.ReasonCode = MqttPubAckReasonCode.NotAuthorized;
                args.Response.ReasonString = "Not Authorized";
                messageInterceptedOnServer = true;
            };

            using (var client1 = mqttFactory.CreateMqttClient())
            {
                var client1Options = new MqttClientOptionsBuilder()
                    .WithTcpServer("localhost")
                    .WithClientId(Guid.NewGuid().ToString())
                    .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V500)
                    .Build();
                
                await client1.ConnectAsync(client1Options, CancellationToken.None);

                using(var client2 = mqttFactory.CreateMqttClient())
                {
                    var client2Options = new MqttClientOptionsBuilder()
                        .WithTcpServer("localhost")
                        .WithClientId(Guid.NewGuid().ToString())
                        .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V500)
                        .Build();
                    await client2.ConnectAsync(client2Options, CancellationToken.None);
                    await client2.SubscribeAsync(testTopic,MqttQualityOfServiceLevel.AtLeastOnce);

                    // publish the message
                    var res = await client1.PublishStringAsync(testTopic, "hello",MqttQualityOfServiceLevel.AtLeastOnce);

                    while (messageInterceptedOnServer == false)
                    {
                        await Task.Delay(300);
                    }

                    await client2.DisconnectAsync();
                    // Now get not authorized
                    Assert.AreEqual(res.ReasonCode, MqttClientPublishReasonCode.NotAuthorized);

                }
                await client1.DisconnectAsync();
            }

            await mqttServer.StopAsync();
        }
    }

It might not be Mqtt standard but only sending NoMatchingSubscribers if you are authorized in the MqttClientSessionsManager class would be a cleaner solution for me. If you have retained messages on I think it is ok that you do not have any subscribers.

eg
if (matchingSubscribersCount == 0 && reasonCode != (int)MqttPubAckReasonCode.NotAuthorized)
{
reasonCode = (int)MqttPubAckReasonCode.NoMatchingSubscribers;
await FireApplicationMessageNotConsumedEvent(applicationMessage, senderId).ConfigureAwait(false);
}

from mqttnet.

chkr1011 avatar chkr1011 commented on May 28, 2024

That is a good idea. But would check for success instead. So that it will never return NoMatchingSubscribers only if it is basically a success and no error etc.

from mqttnet.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.