MQTT Broker in C#

Hello All
Please Help Me to write MQTT broker in C# which can subscribe clients and Publish Messages to Subscribed clients.

Thanks in Advance
Atul Saini

Hi Atul,

Writing an MQTT broker isn’t exactly a small task, if you really want to do it then I suggest you start and share your code, then if anyone wants to contribute help they have the opportunity to do so.

Regards,

Roger

1 Like

Hello Roger
below is my code for broker

using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using MQTTnet;
using MQTTnet.Server;
using Serilog;

namespace MQTTFirstLook.Broker
{
class Program
{
private static int MessageCounter = 0;
private static IMqttServer mqttServer;
static void Main(string args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();

        MqttServerOptionsBuilder options = new MqttServerOptionsBuilder()
            .WithDefaultEndpoint()
            .WithDefaultEndpointPort(707)
            .WithConnectionValidator(OnNewConnection)
            .WithApplicationMessageInterceptor(OnNewMessage);


         mqttServer = new MqttFactory().CreateMqttServer();

        mqttServer.StartAsync(options.Build()).GetAwaiter().GetResult();
        Console.ReadLine();
    }

    public static void OnNewConnection(MqttConnectionValidatorContext context)
    {
        Log.Logger.Information(
                "New connection: ClientId = {clientId}, Endpoint = {endpoint}, CleanSession = {cleanSession}",
                context.ClientId,
                context.Endpoint,
                context.CleanSession);
    }

    public static void OnNewMessage(MqttApplicationMessageInterceptorContext context)
    {
        var payload = context.ApplicationMessage?.Payload == null ? null : Encoding.UTF8.GetString(context.ApplicationMessage?.Payload);

        MessageCounter++;

        Log.Logger.Information(
            "MessageId: {MessageCounter} - TimeStamp: {TimeStamp} -- Message: ClientId = {clientId}, Topic = {topic}, Payload = {payload}, QoS = {qos}, Retain-Flag = {retainFlag}",
            MessageCounter,
            DateTime.Now,
            context.ClientId,
            context.ApplicationMessage?.Topic,
            payload,
            context.ApplicationMessage?.QualityOfServiceLevel,
            context.ApplicationMessage?.Retain);
        PublishMessage("Hi", "Success");
    }
    private static async Task PublishMessage(string message, string topic)
    {
        // Create mqttMessage
        var mqttMessage = new MqttApplicationMessageBuilder()
                            .WithTopic(topic)
                            .WithPayload(message)
                            .WithAtLeastOnceQoS()
                            .WithRetainFlag(false)
                            .WithDupFlag(false)
                            .Build();

        // Publish the message asynchronously
        var result = await mqttServer.PublishAsync(mqttMessage, CancellationToken.None);

        if (result.ReasonCode == MQTTnet.Client.Publishing.MqttClientPublishReasonCode.Success)
            Console.WriteLine("Message published : " + message);
    }
}

}

===============================================

This Will Subscribe Client Successfully and Received Msg From Client Successfully but Don’t send Broadcast Msg to Clients.

Please Help Me

Thanks in Advance
Atul Saini

Hi Atul,

from your line of code:

I would assume you are programming based on the MQTTnet. Which in general seems be a a good idea as Reger mentioned before implementing an MQTT broker from scratch would be a challenging task. And this framework already seems to include a basic broker implementation as well. And some sample code how to implement a basic broker.

But honestly I don’t understand, what you are trying to achieve with your project. In general terms around MQTT you normally a have MQTT-broker (sometimes called MQTT-server), which main responsibility is to wait for client connections and then dispatching incoming messages from this clients to the other connected clients based on their subscription. With this messages he should fullfill all requirements around QOS and retain of messages and session reconnect. Additionally the server may added stuff like user management, permission handling, queue handling, disk persistence. Not taken a deeper look, how complete the broker implementation in the MQTTnet framework is.
A component, which connects two MQTT brokers and allows to forward part or all of the messages from one broker to the other (more precise: messages published on one broker may be published to subscribers connected to another broker) are normally called MQTT-Bridge. In some cases (like the Mosquitto MQTT broker) the bride functionality is already integrated into the broker itself. But a MQTT Bridge maybe implemented as an independent component as well.

So perhaps you might want to share some more details what you are trying to achieve (from a use-case perspective). And how you would like us to help you.

This forum is about the Mosquitto MQTT broker. An open source MQTT broker implementation written in C sponsored by the Cedalo GmbH, which offers additional extension and services around the broker as well. So I am still not sure how to help you.

Dear Norbert
as my code My Broker Work Successfully when a client subscribe then its work ok.
When a client Sent message to broker then it received ok.
but my broker not Broadcast messages to clients.

Dear Atul,
I would assume this is the wrong forum to ask this questions about the MQTTnet based broker implementation. If you would work on a fork/modified Mosquitto broker this would be excactly the right place to ask this kind of questions.
I don’t have detailed knowledge about the MQTTnet framework you are using. And I doubt there are other forum members in this forum with knowledge about the MQTTnet library (and especially the broker implementation of this library).
Looks like there is a gitter forum you may post a message to MQTTnet/community - Gitter More likely to find somebody there able to help you.

1 Like