C#实现MQTT通讯

摘要:public IMqttClient _mqttClient;string serverIP, serverPort, user, pwd;public MqttHelper(string ipAddr, string port, string userNam


一、安装MQTTnet

二、引用dll

using MQTTnet;using MQTTnet.Client;using MQTTnet.Protocol;

三、建立MQTT连接

public IMqttClient _mqttClient;string serverIP, serverPort, user, pwd;public MqttHelper(string ipAddr, string port, string userName, string userPwd){ serverIP = ipAddr; serverPort = port; user = userName; pwd = userPwd;}MqttClientOptions options = null;public Action GetActionSubscribe;public async void ConntionServer{ try { options = new MqttClientOptions { ClientId = Guid.NewGuid.ToString("D") }; options.ChannelOptions = new MqttClientTcpOptions { Server = serverIP, Port = Convert.ToInt32(serverPort) }; options.Credentials = new MqttClientCredentials { Username = user, Password = pwd }; options.CleanSession = true; options.KeepAlivePeriod = TimeSpan.FromSeconds(100.5); options.KeepAliveSendInterval = TimeSpan.FromSeconds(20000); if (null != _mqttClient) { await _mqttClient.DisconnectAsync; _mqttClient = null; } _mqttClient = new MqttFactory.CreateMqttClient; //接收信息 _mqttClient.ApplicationMessageReceived += (sender, args) => { GetActionSubscribe?.Invoke(Encoding.UTF8.GetString(args.ApplicationMessage.Payload)); }; _mqttClient.Connected += (sender, args) => { }; _mqttClient.Disconnected += (sender, args) => { }; await _mqttClient.ConnectAsync(options); } catch (Exception ex) { }}public async void DisConntionServer{ try { if (null != _mqttClient && _mqttClient.IsConnected) { await _mqttClient.DisconnectAsync; _mqttClient.Dispose; _mqttClient = null; } } catch (Exception ex) { }}public async void HeartConntionServer{ try { if (null != _mqttClient && options != null) { await _mqttClient.ConnectAsync(options); } } catch (Exception ex) { }}

四、发布/订阅消息

//发布消息public void SendMessage(string Topic, string Payload){ try { Task.Factory.StartNew(async => { var msg = new MqttApplicationMessage { Topic = Topic, Payload = Encoding.UTF8.GetBytes(Payload), QualityOfServiceLevel = (MqttQualityOfServiceLevel) Enum.Parse(typeof(MqttQualityOfServiceLevel), "1"), Retain = false }; if (null != _mqttClient) { await _mqttClient.PublishAsync(msg); } else { } }); } catch (Exception ex) { }}//订阅消息public async void SubscribeAsync(string Topic){ try { if (_mqttClient == null) return; Thread.Sleep(1000); await _mqttClient.SubscribeAsync( new List { new TopicFilter( Topic, (MqttQualityOfServiceLevel) System.Enum.Parse(typeof (MqttQualityOfServiceLevel), "1")) }); } catch (Exception ex) { }}开源微信小程序记账软件,非常适合个人和公司使用,支持二次开发老板要求设计一套安全高效稳定的第三方接口方案美发行业老板都在找的一款软件,理发店管理系统后起之秀.NET6开源的电商小程序商城支持多商户,值得推荐C#WinForm实操串口通讯使用GtkSharp库实现跨平台C# WinForm实现百家号自动登录上传视频功能VOL.NET6开发MES系统第三篇——基础数据完结C#实现WebSocket服务和通讯VOL.NET6开发MES系统第二篇——基础数据C#实现MQTT通讯

来源:有趣的科技君

相关推荐