C# Accepting Messages From MQTT Server

Introduction:

MQTT is an instant messaging protocol developed by IBM. MQTT is a connection protocol aimed at M2M and the Internet of Things, utilizing a lightweight publish and subscribe message transmission mechanism.

You can directly download the source code of the MQQT service from GitHub, source code address: https://github.com/mqtt/mqtt.github.io/wiki/libraries

Main Content:

Official Document Translation:

The M2Mqtt library provides a main class MqttClient, which represents the MQTT client connected to the broker. You can connect to a broker by providing its IP address or hostname, along with some optional parameters related to the MQTT protocol.

After connecting to the broker, you can use the Publish() method to publish messages to a topic and the Subscribe() method to subscribe to a topic and receive messages published on it.

The MqttClient class is event-based, so you will receive an event when a message is published to a topic you subscribed to. After the message publishing is complete, you can receive events indicating that you have subscribed to or unsubscribed from a topic.

Example with client as the subject:

// create client instance
MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));
// register to message received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
string clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
// subscribe to the topic "/home/temperature" with QoS 2
client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
...
static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) {
    // handle message received
}

Generally, C# clients use the singleton pattern, below is my encapsulated class:

public class MqttClientService
{
    private static volatile MqttClientService _instance = null;
    private static readonly object LockHelper = new object();
    /// <summary>
    /// Create singleton pattern
    /// </summary>
    /// <param name="ipAddress"></param>
    /// <returns></returns>
    public static MqttClientService CreateInstance(string ipAddress)
    {
        if (_instance == null)
        {
            lock (LockHelper)
            {
                if (_instance == null)
                    _instance = new MqttClientService(ipAddress);
            }
        }
        return _instance;
    }
    /// <summary>
    /// Instantiate subscription client
    /// </summary>
    public MqttClient SubscribeClient { get; set; }
    public Action<Object, MqttMsgPublishEventArgs> ClientPublishReceivedAction { get; set; }
    public MqttClientService(string ipAddress)
    {
        // create client instance 
        SubscribeClient = new MqttClient(IPAddress.Parse(ipAddress));
        // register to message received 
        SubscribeClient.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
        string clientId = Guid.NewGuid().ToString();
        SubscribeClient.Connect(clientId);
        // subscribe to the topic "/home/temperature" with QoS 2 
        SubscribeClient.Subscribe(new string[] { "avatar/uploaded" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
    }
    void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
    {
        // handle message received 
        ClientPublishReceivedAction.Invoke(sender, e);
    }
    public void client_MqttMsgPublish(string publishString)
    {
        SubscribeClient.Publish("avatar/signed", Encoding.UTF8.GetBytes(publishString), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
    }
}

Users only need to write the subscribed path in Subscribe.

Related Articles:

  • Quickly Implement MQTT Communication Using MQTTnet

Original article address: https://www.cnblogs.com/dongqinnanren/p/6839319.html

.NET Community News, In-Depth Articles, Welcome to Visit Public Account Article Summary http://www.csharpkit.com

Leave a Comment