M2Mqtt Architecture

The main class of the library is the MqttClient that provides all the methods needed for connecting/disconnecting to/from the broker and for subscribing/publishing to a topic. Moreover, it provides some events raised when a subscribtion/unsubscription operation is completed, when a message sent is published correctly (only in the case of QoS Level 1 and 2), when a message is received and if the client disconnects from broker (for example, due to network problem).

This class executes all network operations (send and receive) by an instance of MqttNetworkChannel class that defines a level of abstraction from the real classes used to access to the network (like Socket and SslStream). It uses the simple Socket class if the conditional compilation symbol SSL isn’t defined, because the developer don’t want to use SSL/TLS feature, or if this symbol is defined but a secure connection isn’t requested when the MqttClient class is instantiated. The SslStream class is used only when the SSL symbol is defined and a secure connection is requested by MqttClient class constructor.


Each MQTT message is implemented by a class that derives from the base class MqttMsgBase that provides the methods for encoding and decoding the length of the payload following the header as protocol specification. It is an abstract class that you can’t instantiate.

All other message classes are defined as MqttMsgXXXX (ex. MqttMsgPublish, MqttMsgSubscribe, …) and they derive from MqttMsgBase implementing the GetBytes() method that create a byte array representation of the current object to send on the network and the Parse() method that create a message object from the byte stream received from the network. They are the bridge between Object Oriented (OO) and network representation world.


There are also some XXXEventArgs classes that derive from EventArgs base class and that are used in the events raised on subscription/unsubcription, published (only for QoS Level 1 and 2) and received message. They define the event model of the library so that the user can receive asynchronous notification when the main operations provided by MQTT protocol are completed.


All the exception classes derive from ApplicationException base class provided by the framework and they represent error on connection, communication and timeout.