您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關C#如何實現MQTT服務端與客戶端通訊功能,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
MQTT(消息隊列遙測傳輸)是ISO 標準(ISO/IEC PRF 20922)下基于發布/訂閱范式的消息協議。它工作在 TCP/IP協議族上,是為硬件性能低下的遠程設備以及網絡狀況糟糕的情況下而設計的發布/訂閱型消息協議,為此,它需要一個消息中間件 。
MQTT是一個基于客戶端-服務器的消息發布/訂閱傳輸協議。MQTT協議是輕量、簡單、開放和易于實現的,這些特點使它適用范圍非常廣泛。在很多情況下,包括受限的環境中,如:機器與機器(M2M)通信和物聯網(IoT)。其在,通過衛星鏈路通信傳感器、偶爾撥號的醫療設備、智能家居、及一些小型化設備中已廣泛使用。
注: 該示例演示統一使用WPF, 簡單MVVM模式演示, 需注意引用 NuGet包
GalaSoft
演示界面:
演示代碼:
public class MainViewModel : ViewModelBase { /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { ClientInsTances = new ObservableCollection<ClientInstance>(); } IMqttServer mqttServer; //MQTT服務端實例 string message; /// <summary> /// 消息 用于界面顯示 /// </summary> public string Message { get { return message; } set { message = value; RaisePropertyChanged(); } } ObservableCollection<ClientInstance> clientInstances; //客戶端登陸緩存信息 /// <summary> /// 客戶端實例 /// </summary> public ObservableCollection<ClientInstance> ClientInsTances { get { return clientInstances; } set { clientInstances = value; RaisePropertyChanged(); } } //開啟MQTT服務 public void OpenMqttServer() { mqttServer = new MqttFactory().CreateMqttServer(); var options = new MqttServerOptions(); //攔截登錄 options.ConnectionValidator = c => { try { Message += string.Format("用戶嘗試登錄:用戶ID:{0}\t用戶信息:{1}\t用戶密碼:{2}", c.ClientId, c.Username, c.Password) + "\r\n"; if (string.IsNullOrWhiteSpace(c.Username)) { Message += string.Format("用戶:{0}登錄失敗,用戶信息為空", c.ClientId) + "\r\n"; c.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return; } //解析用戶名和密碼,這個地方需要改成查找我們自己創建的用戶名和密碼。 if (c.Username == "admin" && c.Password == "123456") { c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted; Message += c.ClientId + " 登錄成功" + "\r\n"; ClientInsTances.Add(new ClientInstance() { ClientID = c.ClientId, UserName = c.Username, PassWord = c.Password }); return; } else { c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; Message += "用戶名密碼錯誤登陸失敗" + "\r\n"; return; } } catch (Exception ex) { Console.WriteLine("登錄失敗:" + ex.Message); c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected; return; } }; //攔截訂閱 options.SubscriptionInterceptor = async context => { try { Message += "用戶" + context.ClientId + "訂閱" + "\r\n"; } catch (Exception ex) { Console.WriteLine("訂閱失敗:" + ex.Message); context.AcceptSubscription = false; } }; //攔截消息 options.ApplicationMessageInterceptor = context => { try { //一般不需要處理消息攔截 // Console.WriteLine(Encoding.UTF8.GetString(context.ApplicationMessage.Payload)); } catch (Exception ex) { Console.WriteLine("消息攔截:" + ex.Message); } }; mqttServer.ClientDisconnected += ClientDisconnected; mqttServer.ClientConnected += MqttServer_ClientConnected; mqttServer.Started += MqttServer_Started; mqttServer.StartAsync(options); } private void MqttServer_Started(object sender, EventArgs e) { Message += "消息服務啟動成功:任意鍵退出" + "\r\n"; } private void MqttServer_ClientConnected(object sender, MqttClientConnectedEventArgs e) { //客戶端鏈接 Message += e.ClientId + "連接" + "\r\n"; } private void ClientDisconnected(object sender, MqttClientDisconnectedEventArgs e) { //客戶端斷開 Message += e.ClientId + "斷開" + "\r\n"; } /// <summary> /// 客戶端推送信息 - 用于測試服務推送 /// </summary> /// <param name="clientID"></param> /// <param name="message"></param> public void SendMessage(string clientID, string message) { mqttServer.PublishAsync(new MqttApplicationMessage { Topic = clientID, QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce, Retain = false, Payload = Encoding.UTF8.GetBytes(message), }); } }
添加MQTT 客戶端登陸實例, 用于保存客戶的登陸信息,如下:
演示界面:
/// <summary> /// 登陸客戶端信息 /// </summary> public class ClientInstance : ViewModelBase { private string clientID; private string userName; private string passWord; /// <summary> /// 識別ID /// </summary> public string ClientID { get { return clientID; } set { clientID = value; RaisePropertyChanged(); } } /// <summary> /// 賬戶 /// </summary> public string UserName { get { return userName; } set { userName = value; RaisePropertyChanged(); } } /// <summary> /// 密碼 /// </summary> public string PassWord { get { return passWord; } set { passWord = value; RaisePropertyChanged(); } } }
演示代碼:
public class MainViewModel : ViewModelBase { /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { clientID = new Random().Next(999, 9999) + ""; //測試隨機生成ClientID } IMqttClient mqttClient; //MQTT客戶端實例 string clientID; //機器ID string message; public string Message //用于接收當前 消息 { get { return message; } set { message = value; RaisePropertyChanged(); } } //開啟MQTT連接 public async void SignMqttServer() { var options = new MqttClientOptionsBuilder() .WithClientId(clientID) //傳遞ClientID .WithTcpServer("127.0.0.1", 1883) //MQTT服務的地址 .WithCredentials("admin", "123456") //傳遞賬號密碼 .WithCleanSession() .Build(); mqttClient = new MqttFactory().CreateMqttClient();// .CreateManagedMqttClient(); mqttClient.Connected += MqttClient_Connected; mqttClient.Disconnected += MqttClient_Disconnected; mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; //創建消息接受事件 await mqttClient.ConnectAsync(options); //await mqttClient.SubscribeAsync(clientID); } private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e) { Message += "收到的信息:" + Encoding.UTF8.GetString(e.ApplicationMessage.Payload) + "\r\n"; } private void MqttClient_Disconnected(object sender, MqttClientDisconnectedEventArgs e) { Message += "客戶端斷開"; } private void MqttClient_Connected(object sender, MqttClientConnectedEventArgs e) { Message += "客戶端已連接" + "\r\n"; mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(clientID).Build()); //關聯服務端訂閱, 用于接受服務端推送信息 } }
演示界面:
實際演示效果(GIF)
上述就是小編為大家分享的C#如何實現MQTT服務端與客戶端通訊功能了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。