Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MQTTNet Listen for Topic Messages

Tags:

c#

asp.net

mqtt

I am integrating MQTT in our existing application, I have used this https://github.com/chkr1011/MQTTnet library for running an embedded MQTT broker.

Currently the following method is used to start the broker:

public async Task StarBrokerAsync()
{
    var optionsBuilder = new MqttServerOptionsBuilder()
        .WithConnectionBacklog(ConnectionBacklog)
        .WithDefaultEndpointPort(Port);

    MqttServer = new MqttFactory().CreateMqttServer();
    await MqttServer.StartAsync(optionsBuilder.Build());
 }

What I want is to listen for messages in a specific topic without creating a separate client at best. I've not found documentation for the library or any similar questions.

Is there any solutions for the problem?


1 Answers

mqttServer.UseApplicationMessageReceivedHandler(e =>
            {
                try
                {
                    string topic = e.ApplicationMessage.Topic;
                    if (string.IsNullOrWhiteSpace(topic) == false)
                    {
                        string payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                        Console.WriteLine($"Topic: {topic}. Message Received: {payload}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message, ex);
                }
            });
like image 105
OrElse Avatar answered Sep 13 '25 18:09

OrElse