首頁 > 軟體

c# mqtt 伺服器端、使用者端簡易例子

2020-09-11 17:33:54

我用的是HslCommunication,本來想用mqttnet的,發現新版本是3.多了,網上的教程都是2.7多了,我項目又比較急,我也懶得研究了,找到了一篇HslCommunication的用法,我整理了下。下面上程式碼

服務端:

using HslCommunication;
using HslCommunication.MQTT;
using System;
using System.Globalization;
using System.Net.Http.Headers;
using System.Text;

namespace MqttTestServer
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass my = new MyClass();
            my.Start();
            Console.ReadLine();
        }
    }

    public class MyClass
    {
        private MqttServer mqttServer = null;
        public void Start()
        {
            mqttServer = new MqttServer();
            mqttServer.ServerStart(6666);
            mqttServer.ClientVerification += OnConnect;
            mqttServer.OnClientDisConnected += OnClientOffline;
            mqttServer.OnClientConnected += OnClientOnline;
            mqttServer.OnClientApplicationMessageReceive += OnClientReceive;
        }

        /// <summary>
        /// 客戶端資訊的字元串
        /// </summary>
        /// <param name="session"></param>
        /// <returns></returns>
        private string ClientInfoString(MqttSession session)
        {
            return string.Format("ID:{0}, 使用者名:{1} ,Ip:{2}", session.ClientId, session.UserName, session.EndPoint);
        }

        /// <summary>
        /// 客戶端下線時候會觸發這個回撥
        /// </summary>
        /// <param name="session"></param>
        private void OnClientOffline(MqttSession session)
        {
            Console.WriteLine("客戶端下線了!" + ClientInfoString(session));
            
        }

        /// <summary>
        /// 客戶端上線的時候會觸發這個回撥
        /// </summary>
        /// <param name="session"></param>
        private void OnClientOnline(MqttSession session)
        {
            Console.WriteLine("客戶端上線了!" + ClientInfoString(session));
        }

        /// <summary>
        /// 當有客戶端連線上來時會觸發這個回撥,返回0是通過,否則就是登入失敗
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="userName"></param>
        /// <param name="passwrod"></param>
        /// <returns></returns>
        private int OnConnect(string clientId, string userName, string passwrod)
        {
            Console.WriteLine("客戶端連線了。");
            return 0;
        }


        /// <summary>
        /// 客戶端收到訊息時觸發
        /// </summary>
        /// <param name="session"></param>
        /// <param name="message"></param>
        private void OnClientReceive(MqttSession session, MqttClientApplicationMessage message)
        {
            Console.WriteLine("客戶端:" + ClientInfoString(session) + "收到訊息了:" + Encoding.UTF8.GetString(message.Payload));
        }
    }
}

 

客戶端:

using System;
using System.Text;
using System.Threading;
using HslCommunication;
using HslCommunication.MQTT;

namespace MqttTestClient
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
            mc.Start();

            mc.Connect();//連線
            mc.Regist();//註冊

            Console.WriteLine("輸入“send”傳送訊息");
            string s = Console.ReadLine();
            if (s == "send")
            {
                Console.WriteLine("我傳送成功了");
                mc.SendMsg();
            }

            Console.ReadLine();
        }

        public class MyClass
        {
            private MqttClient mqttClient = null;
            public void Start()
            {
                mqttClient = new MqttClient(new MqttConnectionOptions()
                {
                    ClientId = "ABC",
                    IpAddress = "127.0.0.1",
                    Port = 6666,
                    Credentials = new MqttCredential("admin", "admin"),   // 設定了使用者名和密碼
                });
            }

            public void Connect()
            {
                // 連線
                OperateResult connect = mqttClient.ConnectServer();
                if (connect.IsSuccess)
                {
                    Console.WriteLine("Success");
                }
                else
                {
                    Console.WriteLine("Failed");
                }
            }

            public void SendMsg()
            {
                // 測試釋出
                mqttClient.PublishMessage(new MqttApplicationMessage()
                {
                    Topic = "A",                                                      // 主題
                    QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,     // 訊息等級
                    Payload = Encoding.UTF8.GetBytes("This is test message!"),        // 資料
                    Retain = false,                                                   // 是否保留
                });
            }

            public void Regist()
            {
                // 訂閱測試,在label1上顯示結果
                mqttClient.OnMqttMessageReceived += MqttClient_OnMqttMessageReceived; // 呼叫一次即可
                mqttClient.SubscribeMessage("A");     // 訂閱A的主題
            }

            private void MqttClient_OnMqttMessageReceived(string topic, byte[] payload)
            {
          //topic是主題名字。payload是訊息內容; Console.WriteLine(
"我收到了訊息了"); string s = Encoding.UTF8.GetString(payload); Console.WriteLine(s); } } } }

 

運行結果:

 


IT145.com E-mail:sddin#qq.com