Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the Communication function between MQTT Server and client in C #

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this issue, the editor will bring you about how to realize the communication function between MQTT server and client in C#. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.

About MQTT

MQTT (message queuing Telemetry Transport) is a message protocol based on publish / subscribe paradigm under the ISO standard (ISO/IEC PRF 20922). It works on the TCP/IP protocol family and is a publish / subscribe messaging protocol designed for remote devices with low hardware performance and poor network conditions. For this reason, it needs a message middleware.

MQTT is a client-server based message publish / subscribe transport protocol. MQTT protocol is lightweight, simple, open and easy to implement, which makes it suitable for a wide range of applications. In many cases, including constrained environments, such as machine-to-machine (M2M) communication and the Internet of things (IoT). It has been widely used in satellite link communication sensors, occasionally dialed medical devices, smart homes, and some miniaturized devices.

MQTT example

Note: this example demonstrates the unified use of WPF and simple MVVM mode. Note that you should refer to the NuGet package GalaSoft.

MQTT server establishment:

Demo interface:

Demo code:

Public class MainViewModel: ViewModelBase {/ Initializes a new instance of the MainViewModel class. / public MainViewModel () {ClientInsTances = new ObservableCollection ();} IMqttServer mqttServer; / / MQTT server instance string message; / message is used to display / public string Message {get {return message;} set {message = value; RaisePropertyChanged () }} ObservableCollection clientInstances; / / client login cache information / client instance / public ObservableCollection ClientInsTances {get {return clientInstances;} set {clientInstances = value; RaisePropertyChanged () }} / / Open MQTT service public void OpenMqttServer () {mqttServer = new MqttFactory () .CreateMqttServer (); var options = new MqttServerOptions () / / blocking login options.ConnectionValidator = c = > {try {Message + = string.Format ("user attempted login: user ID: {0}\ t user information: {1}\ t user password: {2}", c.ClientId, c.Username, c.Password) + "\ r\ n" If (string.IsNullOrWhiteSpace (c.Username)) {Message + = string.Format ("user: {0} login failed, user information is empty", c.ClientId) + "\ r\ n"; c.ReturnCode = MQTTnet.Protocol.MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; return } / / parse the user name and password, and this place needs to be changed to find the user name and password we created. If (c.Username = = "admin" & & c.Password = = "123456") {c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted; Message + = c.ClientId + "login successful" + "\ r\ n" ClientInsTances.Add (new ClientInstance () {ClientID = c.ClientId, UserName = c.Username, PassWord = c.Password}); return } else {c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword; Message + = "user name password failed login" + "\ r\ n"; return }} catch (Exception ex) {Console.WriteLine ("login failed:" + ex.Message); c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedIdentifierRejected; return;}} / / blocking subscription options.SubscriptionInterceptor = async context = > {try {Message + = "user" + context.ClientId + "subscription" + "\ r\ n" } catch (Exception ex) {Console.WriteLine ("subscription failed:" + ex.Message); context.AcceptSubscription = false;}} / / intercepting messages options.ApplicationMessageInterceptor = context = > {try {/ / message interception / / Console.WriteLine (Encoding.UTF8.GetString (context.ApplicationMessage.Payload)) is generally not required } catch (Exception ex) {Console.WriteLine ("message interception:" + 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 + = "message service started successfully: any key exits" + "\ r\ n";} private void MqttServer_ClientConnected (object sender, MqttClientConnectedEventArgs e) {/ / client link Message + = e.ClientId + "connection" + "\ r\ n" } private void ClientDisconnected (object sender, MqttClientDisconnectedEventArgs e) {/ / client disconnect Message + = e.ClientId + "disconnect" + "\ r\ n" } / client push information-used to test service push / public void SendMessage (string clientID, string message) {mqttServer.PublishAsync (new MqttApplicationMessage {Topic = clientID, QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce) Retain = false, Payload = Encoding.UTF8.GetBytes (message),}) }}

Add a MQTT client login instance to save the customer's login information, as follows:

Demo interface:

/ login client information / public class ClientInstance: ViewModelBase {private string clientID; private string userName; private string passWord; / identify ID / public string ClientID {get {return clientID;} set {clientID = value; RaisePropertyChanged () } / account / public string UserName {get {return userName;} set {userName = value; RaisePropertyChanged ();} / password / public string PassWord {get {return passWord } set {passWord = value; RaisePropertyChanged ();} MQTT client establishment:

Demo code:

Public class MainViewModel: ViewModelBase {/ Initializes a new instance of the MainViewModel class. / / public MainViewModel () {clientID = new Random (). Next (999,9999) + "; / / Test randomly generates ClientID} IMqttClient mqttClient; / / MQTT client instance string clientID; / / Machine ID string message; public string Message / / to receive the current message {get {return message } set {message = value; RaisePropertyChanged () }} / / Open MQTT connection public async void SignMqttServer () {var options = new MqttClientOptionsBuilder () .WithClientId (clientID) / pass ClientID .WithTcpServer ("127.0.0.1", 1883) / / address of the MQTT service .WithCredentials ("admin") "123456") / / pass the account password. WithCleanSession () .build () MqttClient = new MqttFactory (). CreateMqttClient (); / / .CreateManagedMqttClient (); mqttClient.Connected + = MqttClient_Connected; mqttClient.Disconnected + = MqttClient_Disconnected; mqttClient.ApplicationMessageReceived + = MqttClient_ApplicationMessageReceived; / / create message acceptance event await mqttClient.ConnectAsync (options); / / await mqttClient.SubscribeAsync (clientID) } private void MqttClient_ApplicationMessageReceived (object sender, MqttApplicationMessageReceivedEventArgs e) {Message + = "received message: + Encoding.UTF8.GetString (e.ApplicationMessage.Payload) +"\ r\ n ";} private void MqttClient_Disconnected (object sender, MqttClientDisconnectedEventArgs e) {Message + =" client disconnected " } private void MqttClient_Connected (object sender, MqttClientConnectedEventArgs e) {Message + = "client connected" + "\ r\ n"; mqttClient.SubscribeAsync (new TopicFilterBuilder (). WithTopic (clientID). Build ()); / / Associated server subscription to receive server push information}}

Demo interface:

Actual demonstration effect (GIF)

The above is the editor for you to share the C# how to achieve MQTT server and client communication function, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report