# 2.1.3.Install M2Mqtt by Nuget, Example code

* 1.Requirement: .NET Framework 4.5
* 2.Open Nuget console and input "Install-Package M2Mqtt"
* 3.Example code:
  * 1.Publisher:

    ```
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using uPLibrary.Networking.M2Mqtt;
    using uPLibrary.Networking.M2Mqtt.Messages;

    namespace MQTTPublisher
    {
        class Program
        {
            static void Main(string[] args)
            {
                var id = args[0];
                var topic = args[1];

                MqttClient client = new MqttClient("127.0.0.1");
                //若有輸入user, password, 接收端也要一樣的user, password
                client.Connect(id);

                //若要知道有沒有發送出去可以增加監聽發送後的Event
                client.MqttMsgPublished += new MqttClient.MqttMsgPublishedEventHandler(client_MqttMsgPublished);
    ```

```
                  Stopwatch sw = new Stopwatch();
                  sw.Start();
                  for (int i = 0; i < 10000; i++)
                  {
                      //publish 最後一的parameter 是retain, 會決定是否保留著最後一個message 
                      ushort t = client.Publish(topic, Encoding.UTF8.GetBytes("XXXXXtestmessage, "
            + Guid.NewGuid().ToString() + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + ", times: " + i),
                      MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, true);
                      //
                      Thread.Sleep(1000);
                  }
                  sw.Stop();
                  Console.WriteLine("花費時間..... {0}", sw.Elapsed);
                  //Console.ReadLine();
                  client.Disconnect();

              }
              private static void client_MqttMsgPublished(object sender, MqttMsgPublishedEventArgs e)
              {
                  Console.WriteLine("Message Published");
                  Console.WriteLine(e.IsPublished);
                  Console.WriteLine(e.MessageId);
              }
          }
      }
```

* 2.Subscriber:

```
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading;
        using System.Threading.Tasks;
        using uPLibrary.Networking.M2Mqtt;
        using uPLibrary.Networking.M2Mqtt.Messages;

        namespace MQTTSubscriber
        {
            class Program
            {
                static void Main(string[] args)
                {
                    var id = args[0];
                    var topic = args[1];

                    MqttClient client = new MqttClient("127.0.0.1");

                    //如果有出現相同的id 會把前一個id 給踢掉
                    //要與發送端相同
                    client.Connect(id);

                    //topic 可以使用 topic1/#, topic2/+ 去接收相似的topic ，有點類似 sql like 的功能但限制較多
                    string[] topic2 = { topic };

                    byte[] qoslevels = { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE };

                    client.Subscribe(topic2, qoslevels);

                        client.MqttMsgPublishReceived += new MqttClient.MqttMsgPublishEventHandler(client_PublishArrived);


                    //client.MqttMsgPublishReceived += new MqttClient.MqttMsgPublishEventHandler(client_PublishArrived);

                    //Thread.Sleep(100000);
                    Console.ReadLine();
                    client.Disconnect();
                }
                private static void client_PublishArrived(object sender, MqttMsgPublishEventArgs e)
                {
                    Console.WriteLine("Message Received");
                    Console.WriteLine(e.Topic);
                    Console.WriteLine(Encoding.UTF8.GetString(e.Message));
                }
            }
        }
```

* 4.心得:
  * 1.Publisher與Subscriber的ID不要相同
  * 2.Publisher與Subscriber的Topic要相同

![](/files/-M4M0IOerJdHNCY5FVcq)

![](/files/-M4M0IOgGPSL9z5GbgnY)

![](/files/-M4M0IOiKDqwL5XlNgUH)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jen-hsuan-hsieh.gitbook.io/protocol/chapter2-protocol-for-iot/21mqtt/213install-m2mqtt-by-nuget-example-code.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
