Hello, here's an example for you.

Remember to replace "mqtt.server.com" with the actual address of your MQTT server, 1883 with the appropriate port number, and "your/topic" with the desired MQTT topic. Additionally, you can modify the client identifier and payload message as needed.

This code establishes a connection to the MQTT server, subscribes to the specified topic, sends a message, waits for a few seconds to receive any incoming messages, and then stops the MQTT client.

using System;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Extensions.ManagedClient;
class Program
    static async Task Main(string[] args)
        var factory = new MqttFactory();
        var mqttClient = factory.CreateManagedMqttClient();
        var options = new ManagedMqttClientOptionsBuilder()
            .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
            .WithClientOptions(new MqttClientOptionsBuilder()
                .WithTcpServer("mqtt.server.com", 1883) // Replace with your MQTT server address and port
                .WithClientId("ClientId") // Replace with a client identifier
                .Build())
            .Build();
        await mqttClient.StartAsync(options);
        string topic = "your/topic";
        await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).Build());
        mqttClient.UseApplicationMessageReceivedHandler(e =>
            Console.WriteLine($"Received message: {e.ApplicationMessage.Payload}");
        string message = "Hello, MQTT!";
        await mqttClient.PublishAsync(new MqttApplicationMessageBuilder()
            .WithTopic(topic)
            .WithPayload(message)
            .Build());
        await Task.Delay(TimeSpan.FromSeconds(5));
        await mqttClient.StopAsync();