Using Mqttnet to build an MQTT Server

Source: Internet
Author: User


Objective


Mqttnet is the. NET open source Class library of the MQTT protocol.


Mqttnet is a. NET library for MQTT based communication. IT provides a MQTT client and a MQTT server. The implementation is based on the documentation from http://mqtt.org/.


The MQTT protocol is an Instant messaging protocol developed by IBM that is likely to be an important part of the internet of Things, http://mqtt.org/.


MQTT is a machine-to-machine (ATM)/"Internet of Things" connectivity protocol. It is designed as an extremely lightweight publish/subscribe messaging transport. It is useful-connections with remote locations where a small code footprint is required and/or network bandwidth are at A premium. For example, it had been used in sensors communicating to a broker via satellite link, over occasional dial-up connections With healthcare providers, and in a range of home automation and small device scenarios. It is also ideal for mobile applications because of its small size, low power usage, minimised data packets, and efficient Distribution of information to one or many receivers


Find the official recommended server software via Https://github.com/mqtt/mqtt.github.io/wiki/servers, such as Apache Apollo (ACTIVEMQ branch), by https:// Github.com/mqtt/mqtt.github.io/wiki/libraries can find the recommended client class library.


Mqttnet


Through the NuGet search Mqtt found mqttnet, it is not the most downloaded, nor the official recommendation list, mainly because both the client and the service side, so began to download the trial, the results proved that there is a pit, the source code in the vs2015 can not be opened .



Open Source Address: https://github.com/chkr1011/MQTTnet



First, the official console program is changed to WinForm, the interface is as follows:





Public partial class Form1 : Form
    {

        Private MqttServer mqttServer = null;
        Private MqttClient mqttClient = null;

        Public Form1()
        {
            InitializeComponent();
        }

        Private void button_Start server_Click(object sender, EventArgs e)
        {

            MqttTrace.TraceMessagePublished += MqttTrace_TraceMessagePublished;
        

            If (this.mqttServer == null)
            {
                Try
                {
                    Var options = new MqttServerOptions
                    {
                        ConnectionValidator = p =>
                        {
                            If (p.ClientId == "SpecialClient")
                            {
                                If (p.Username != "USER" || p.Password != "PASS")
                                {
                                    Return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                                }
                            }

                            Return MqttConnectReturnCode.ConnectionAccepted;
                        }
                    };

                    mqttServer = new MqttServerFactory().CreateMqttServer(options);

                }
                Catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    Return;

                }
            }
            mqttServer.Start();

            this.txt_Server.AppendText( $">> Starts successfully..." + Environment.NewLine);
        }

        Private void MqttTrace_TraceMessagePublished(object sender, MqttTraceMessagePublishedEventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                this.txt_Server.AppendText($">> [{e.ThreadId}] [{e.Source}] [{e.Level}]: {e.Message}" + Environment.NewLine);
                If (e.Exception != null)
                {
                    this.txt_server.AppendText( e.Exception + Environment.NewLine);
                }
            }));
        }

        Private void button_stop server_Click(object sender, EventArgs e)
        {
            If (mqttServer != null)
            {
                mqttServer.Stop();
            }
            this.txt_server.AppendText( $">> Stops successfully" + Environment.NewLine);
        }

        Private async void button_start client_Click(object sender, EventArgs e)
        {
            If (this.mqttClient == null)
            {
                Var options = new MqttClientOptions
                {
                    Server = "192.168.2.54",
                    ClientId = "zbl",
                    CleanSession = true
                };
                this.mqttClient = new MqttClientFactory().CreateMqttClient(options);
                this.mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
                this.mqttClient.Connected += MqttClient_Connected;
                this.mqttClient.Disconnected += MqttClient_Disconnected;


            }
            Try
            {
                Await this.mqttClient.ConnectAsync();
            }
            Catch(Exception ex)
            {
                this.txt_client.AppendText( $"### CONNECTING FAILED ###" + Environment.NewLine);
            }


        }

        Private void MqttClient_Connected(object sender, EventArgs e)
        {

            this.Invoke(new Action( async () =>
            {

                this.txt_client.AppendText( $"### CONNECTED WITH SERVER ###" + Environment.NewLine);
                Await this.mqttClient.SubscribeAsync(new List<TopicFilter>{
                        New TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
                    });
                this.txt_client.AppendText($"### SUBSCRIBED ###" + Environment.NewLine);
            }));
        }

        Private void MqttClient_Disconnected(object sender, EventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                this.txt_client.AppendText( $"### DISCONNECTED FROM SERVER ###" + Environment.NewLine);

            }));
        }

        Private void MqttClient_ApplicationMessageReceived(object sender, MQTTnet.Core.MqttApplicationMessageReceivedEventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                this.txt_client.AppendText( $">> Topic:{e.ApplicationMessage.Topic} Payload:{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)} QoS:{e.ApplicationMessage.QualityOfServiceLevel} Retain:{ e.ApplicationMessage.Retain}" + Environment.NewLine);

            }));
        }

        Private async void button_stop client_Click(object sender, EventArgs e)
        {
            If (this.mqttClient != null)
            {
                Await this.mqttClient.DisconnectAsync();
            }
            this.txt_client.AppendText( $">> Stops successfully" + Environment.NewLine);
        }

        Private async void button_send_click(object sender, EventArgs e)
        {

            //var options = new MqttClientOptions
            //{
            // Server = "localhost"//};
             //var client = new MqttClientFactory().CreateMqttClient(options);

             //await client.ConnectAsync();

             Var applicationMessage = new MqttApplicationMessage(this.txt_topic.Text,
                 Encoding.UTF8.GetBytes(this.txt_message.Text), MqttQualityOfServiceLevel.AtMostOnce, false);

             Await this.mqttClient.PublishAsync(applicationMessage);

         }

         Private void button_clear server_Click(object sender, EventArgs e)
         {
             this.txt_server.Text = "";
         }
     }
Form1.cs


Note that following the author's instructions is


while (true)
{
    Console.ReadLine();

    var applicationMessage = new MqttApplicationMessage(
        "A/B/C",
        Encoding.UTF8.GetBytes("Hello World"),  MqttQualityOfServiceLevel.AtLeastOnce, false
    );

    await client.PublishAsync(applicationMessage);
}


The client can not receive the message, change to mqttqualityofservicelevel.atmostonce on it, to find a problem when trying to download source debugging because vs2015 can not open the project also toss a while. This question was submitted to issues, expecting the author to reply.



Finally, it is recommended to use Apache Apollo, a few blog post more useful The simple introduction of the MQTT protocol and server installation, writing and MQTT server communication Android client program, reference "Mqtt" under Windows to build an MQTT server



After setting up the MQTT server, we need to implement the client function separately in the Esp8266 module and mobile app, and then to be continued later ....






Using Mqttnet to build an MQTT Server


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.