mqttnet 详解_mqttnet3.0用法

mqttnet 详解_mqttnet3.0用法1///开源库地址:https://github.com/chkr1011/MQTTnet2///对应文档:https://github.com/chkr1011/MQTTnet/wiki/Client34usingMQTTnet;5usingMQTTnet.Client;6usingMQTTnet.Client.Options;7usingSystem;8usingSystem.T…

大家好,又见面了,我是你们的朋友全栈君。

1 ///开源库地址:https://github.com/chkr1011/MQTTnet

2 ///对应文档:https://github.com/chkr1011/MQTTnet/wiki/Client

3

4 usingMQTTnet;5 usingMQTTnet.Client;6 usingMQTTnet.Client.Options;7 usingSystem;8 usingSystem.Text;9 usingSystem.Threading;10 usingSystem.Threading.Tasks;11 usingSystem.Windows.Forms;12

13 namespaceMqttServerTest14 {15 public partial classmqtt测试工具 : Form16 {17 private IMqttClient mqttClient = null;18 private bool isReconnect = true;19

20 publicmqtt测试工具()21 {22 InitializeComponent();23 }24

25 private void Form1_Load(objectsender, EventArgs e)26 {27

28 }29

30 private async void BtnPublish_Click(objectsender, EventArgs e)31 {32 awaitPublish();33 }34

35 private async void BtnSubscribe_ClickAsync(objectsender, EventArgs e)36 {37 awaitSubscribe();38 }39

40 private asyncTask Publish()41 {42 string topic =txtPubTopic.Text.Trim();43

44 if (string.IsNullOrEmpty(topic))45 {46 MessageBox.Show(“发布主题不能为空!”);47 return;48 }49

50 string inputString =txtSendMessage.Text.Trim();51 try

52 {53

54 var message = newMqttApplicationMessageBuilder()55 .WithTopic(topic)56 .WithPayload(inputString)57 .WithExactlyOnceQoS()58 .WithRetainFlag()59 .Build();60

61 awaitmqttClient.PublishAsync(message);62 }63 catch(Exception ex)64 {65

66 Invoke((new Action(() =>

67 {68 txtReceiveMessage.AppendText($”发布主题失败!” + Environment.NewLine + ex.Message +Environment.NewLine);69 })));70 }71

72

73

74

75 }76

77 private asyncTask Subscribe()78 {79 string topic =txtSubTopic.Text.Trim();80

81 if (string.IsNullOrEmpty(topic))82 {83 MessageBox.Show(“订阅主题不能为空!”);84 return;85 }86

87 if (!mqttClient.IsConnected)88 {89 MessageBox.Show(“MQTT客户端尚未连接!”);90 return;91 }92

93 //Subscribe to a topic

94 await mqttClient.SubscribeAsync(newTopicFilterBuilder()95 .WithTopic(topic)96 .WithAtMostOnceQoS()97 .Build()98 );99 Invoke((new Action(() =>

100 {101 txtReceiveMessage.AppendText($”已订阅[{topic}]主题{Environment.NewLine}”);102 })));103

104 }105

106 private asyncTask ConnectMqttServerAsync()107 {108 //Create a new MQTT client.

109

110 if (mqttClient == null)111 {112 try

113 {114 var factory = newMqttFactory();115 mqttClient =factory.CreateMqttClient();116

117 var options = newMqttClientOptionsBuilder()118 .WithTcpServer(txtIp.Text, Convert.ToInt32(txtPort.Text)).WithCredentials(txtUsername.Text, txtPsw.Text).WithClientId(txtClientId.Text) //Port is optional

119 .Build();120

121

122 awaitmqttClient.ConnectAsync(options, CancellationToken.None);123 Invoke((new Action(() =>

124 {125 txtReceiveMessage.AppendText($”连接到MQTT服务器成功!” +txtIp.Text);126 })));127 mqttClient.UseApplicationMessageReceivedHandler(e =>

128 {129

130 Invoke((new Action(() =>

131 {132 txtReceiveMessage.AppendText($”收到订阅消息!” +Encoding.UTF8.GetString(e.ApplicationMessage.Payload));133 })));134

135 });136 }137 catch(Exception ex)138 {139

140 Invoke((new Action(() =>

141 {142 txtReceiveMessage.AppendText($”连接到MQTT服务器失败!” + Environment.NewLine + ex.Message +Environment.NewLine);143 })));144 }145 }146 }147

148 private void MqttClient_Connected(objectsender, EventArgs e)149 {150 Invoke((new Action(() =>

151 {152 txtReceiveMessage.Clear();153 txtReceiveMessage.AppendText(“已连接到MQTT服务器!” +Environment.NewLine);154 })));155 }156

157 private void MqttClient_Disconnected(objectsender, EventArgs e)158 {159 Invoke((new Action(() =>

160 {161 txtReceiveMessage.Clear();162 DateTime curTime = newDateTime();163 curTime =DateTime.UtcNow;164 txtReceiveMessage.AppendText($”>> [{curTime.ToLongTimeString()}]”);165 txtReceiveMessage.AppendText(“已断开MQTT连接!” +Environment.NewLine);166 })));167

168 //Reconnecting

169 if(isReconnect)170 {171 Invoke((new Action(() =>

172 {173 txtReceiveMessage.AppendText(“正在尝试重新连接” +Environment.NewLine);174 })));175

176 var options = newMqttClientOptionsBuilder()177 .WithClientId(txtClientId.Text)178 .WithTcpServer(txtIp.Text, Convert.ToInt32(txtPort.Text))179 .WithCredentials(txtUsername.Text, txtPsw.Text)180 //.WithTls()

181 .WithCleanSession()182 .Build();183 Invoke((new Action(async () =>

184 {185 await Task.Delay(TimeSpan.FromSeconds(5));186 try

187 {188 awaitmqttClient.ConnectAsync(options);189 }190 catch

191 {192 txtReceiveMessage.AppendText(“### RECONNECTING FAILED ###” +Environment.NewLine);193 }194 })));195 }196 else

197 {198 Invoke((new Action(() =>

199 {200 txtReceiveMessage.AppendText(“已下线!” +Environment.NewLine);201 })));202 }203 }204

205 private void MqttClient_ApplicationMessageReceived(objectsender, MqttApplicationMessageReceivedEventArgs e)206 {207 Invoke((new Action(() =>

208 {209 txtReceiveMessage.AppendText($”>> {“### RECEIVED APPLICATION MESSAGE ###”}{Environment.NewLine}”);210 })));211 Invoke((new Action(() =>

212 {213 txtReceiveMessage.AppendText($”>> Topic = {e.ApplicationMessage.Topic}{Environment.NewLine}”);214 })));215 Invoke((new Action(() =>

216 {217 txtReceiveMessage.AppendText($”>> Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}”);218 })));219 Invoke((new Action(() =>

220 {221 txtReceiveMessage.AppendText($”>> QoS = {e.ApplicationMessage.QualityOfServiceLevel}{Environment.NewLine}”);222 })));223 Invoke((new Action(() =>

224 {225 txtReceiveMessage.AppendText($”>> Retain = {e.ApplicationMessage.Retain}{Environment.NewLine}”);226 })));227 }228

229 private void btnLogIn_Click(objectsender, EventArgs e)230 {231 isReconnect = true;232 Task.Run(async () => { awaitConnectMqttServerAsync(); });233 }234

235 private void btnLogout_Click(objectsender, EventArgs e)236 {237 isReconnect = false;238 Task.Run(async () => { awaitmqttClient.DisconnectAsync(); });239 }240

241 }242 }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/152856.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • navicat for mysql 15.4 激活码_通用破解码

    navicat for mysql 15.4 激活码_通用破解码,https://javaforall.cn/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

  • 卷积神经网络卷积层和池化层的作用(卷积神经网络的重要性)

    链接:https://www.zhihu.com/question/36686900/answer/130890492个人觉得主要是两个作用:1.invariance(不变性),这种不变性包括translation(平移),rotation(旋转),scale(尺度)2.保留主要的特征同时减少参数(降维,效果类似PCA)和计算量,防止过拟合,提高模型泛化能力(1

  • JRTPLIB 3.9.1文档翻译

    JRTPLIB 3.9.1文档翻译MainPageJRTPLIBAuthor:      JoriLiesenborgs      DevelopedattheTheExpertiseCentreforDigitalMedia(EDM),aresearchinstituteoftheHasseltUniversityAcknowledg

  • 小代码改进

    小代码改进

  • nginx面试常见问题[通俗易懂]

    nginx面试常见问题[通俗易懂]Nginx的并发能力在同类型网页服务器中的表现,相对而言是比较好的,因此受到了很多企业的青睐,我国使用Nginx网站的知名用户包括腾讯、淘宝、百度、京东、新浪、网易等等。Nginx是网页服务器运维人员必备技能之一,下面为大家整理了一些比较常见的Nginx相关面试题,仅供参考:1、请解释一下什么是Nginx?Nginx是一个web服务器和反向代理服务器,用于HTTP、HTTPS、SMTP、P…

  • 零散学习笔记(一)—-单相逆变电路设计

    零散学习笔记(一)—-单相逆变电路设计这几天帮别人设计然后画一个电路图,只设计电路图,没有具体实现功能。这题是一道电赛题,大家都知道设计一个电路简单,但是要具体实现功能可不是那么简单的。而本文章是最简单的一部分—电路部分,不涉及程序部分和调试。AC-DC电路设计电源输入电压为220V交流电压,在一般设计中只要是输入为220V交流电肯定需要将交流电转换成直流电压。一般有两个方法:模电方法:使用转换电路——整流(几个二极管组合起来把正负电压变成单向)–滤波(使波形平滑)–稳压(固定输出)–直流电压数电方法:使用DC-AC芯片进行转换(博

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号