您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

295 行
8.7 KiB

  1. using System;
  2. using System.Text;
  3. using System.Threading.Tasks;
  4. using Windows.Security.Cryptography.Certificates;
  5. using Windows.UI.Core;
  6. using Windows.UI.Xaml;
  7. using MQTTnet.Core;
  8. using MQTTnet.Core.Client;
  9. using MQTTnet.Core.Diagnostics;
  10. using MQTTnet.Core.Packets;
  11. using MQTTnet.Core.Protocol;
  12. using MQTTnet.Core.Server;
  13. using MQTTnet.Implementations;
  14. namespace MQTTnet.TestApp.UniversalWindows
  15. {
  16. public sealed partial class MainPage
  17. {
  18. private IMqttClient _mqttClient;
  19. public MainPage()
  20. {
  21. InitializeComponent();
  22. MqttNetTrace.TraceMessagePublished += OnTraceMessagePublished;
  23. }
  24. private async void OnTraceMessagePublished(object sender, MqttNetTraceMessagePublishedEventArgs e)
  25. {
  26. await Trace.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
  27. {
  28. var text = $"[{e.TraceMessage.Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{e.TraceMessage.Level}] [{e.TraceMessage.Source}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Message}]{Environment.NewLine}";
  29. if (e.TraceMessage.Exception != null)
  30. {
  31. text += $"{e.TraceMessage.Exception}{Environment.NewLine}";
  32. }
  33. Trace.Text += text;
  34. });
  35. }
  36. private async void Connect(object sender, RoutedEventArgs e)
  37. {
  38. BaseMqttClientOptions options = null;
  39. if (UseTcp.IsChecked == true)
  40. {
  41. options = new MqttClientTcpOptions
  42. {
  43. Server = Server.Text
  44. };
  45. }
  46. if (UseWs.IsChecked == true)
  47. {
  48. options = new MqttClientWebSocketOptions
  49. {
  50. Uri = Server.Text
  51. };
  52. }
  53. if (options == null)
  54. {
  55. throw new InvalidOperationException();
  56. }
  57. options.UserName = User.Text;
  58. options.Password = Password.Text;
  59. options.ClientId = ClientId.Text;
  60. options.TlsOptions.UseTls = UseTls.IsChecked == true;
  61. options.TlsOptions.IgnoreCertificateChainErrors = true;
  62. options.TlsOptions.IgnoreCertificateRevocationErrors = true;
  63. options.TlsOptions.AllowUntrustedCertificates = true;
  64. try
  65. {
  66. if (_mqttClient != null)
  67. {
  68. await _mqttClient.DisconnectAsync();
  69. }
  70. var factory = new MqttClientFactory();
  71. _mqttClient = factory.CreateMqttClient();
  72. await _mqttClient.ConnectAsync(options);
  73. }
  74. catch (Exception exception)
  75. {
  76. Trace.Text += exception + Environment.NewLine;
  77. }
  78. }
  79. private async void Publish(object sender, RoutedEventArgs e)
  80. {
  81. if (_mqttClient == null)
  82. {
  83. return;
  84. }
  85. try
  86. {
  87. var qos = MqttQualityOfServiceLevel.AtMostOnce;
  88. if (QoS1.IsChecked == true)
  89. {
  90. qos = MqttQualityOfServiceLevel.AtLeastOnce;
  91. }
  92. if (QoS2.IsChecked == true)
  93. {
  94. qos = MqttQualityOfServiceLevel.ExactlyOnce;
  95. }
  96. var payload = new byte[0];
  97. if (Text.IsChecked == true)
  98. {
  99. payload = Encoding.UTF8.GetBytes(Payload.Text);
  100. }
  101. if (Base64.IsChecked == true)
  102. {
  103. payload = Convert.FromBase64String(Payload.Text);
  104. }
  105. var message = new MqttApplicationMessage(
  106. Topic.Text,
  107. payload,
  108. qos,
  109. Retain.IsChecked == true);
  110. await _mqttClient.PublishAsync(message);
  111. }
  112. catch (Exception exception)
  113. {
  114. Trace.Text += exception + Environment.NewLine;
  115. }
  116. }
  117. private async void Disconnect(object sender, RoutedEventArgs e)
  118. {
  119. try
  120. {
  121. await _mqttClient.DisconnectAsync();
  122. }
  123. catch (Exception exception)
  124. {
  125. Trace.Text += exception + Environment.NewLine;
  126. }
  127. }
  128. private void Clear(object sender, RoutedEventArgs e)
  129. {
  130. Trace.Text = string.Empty;
  131. }
  132. private async void Subscribe(object sender, RoutedEventArgs e)
  133. {
  134. if (_mqttClient == null)
  135. {
  136. return;
  137. }
  138. try
  139. {
  140. var qos = MqttQualityOfServiceLevel.AtMostOnce;
  141. if (SubscribeQoS1.IsChecked == true)
  142. {
  143. qos = MqttQualityOfServiceLevel.AtLeastOnce;
  144. }
  145. if (SubscribeQoS2.IsChecked == true)
  146. {
  147. qos = MqttQualityOfServiceLevel.ExactlyOnce;
  148. }
  149. await _mqttClient.SubscribeAsync(new TopicFilter(SubscribeTopic.Text, qos));
  150. }
  151. catch (Exception exception)
  152. {
  153. Trace.Text += exception + Environment.NewLine;
  154. }
  155. }
  156. private async void Unsubscribe(object sender, RoutedEventArgs e)
  157. {
  158. if (_mqttClient == null)
  159. {
  160. return;
  161. }
  162. try
  163. {
  164. await _mqttClient.UnsubscribeAsync(SubscribeTopic.Text);
  165. }
  166. catch (Exception exception)
  167. {
  168. Trace.Text += exception + Environment.NewLine;
  169. }
  170. }
  171. // This code is for the Wiki at GitHub!
  172. // ReSharper disable once UnusedMember.Local
  173. private async Task WikiCode()
  174. {
  175. var mqttClient = new MqttClientFactory().CreateMqttClient();
  176. // ----------------------------------
  177. var tcpOptions = new MqttClientTcpOptions
  178. {
  179. Server = "broker.hivemq.org",
  180. ClientId = "TestClient"
  181. };
  182. await mqttClient.ConnectAsync(tcpOptions);
  183. // ----------------------------------
  184. var secureTcpOptions = new MqttClientTcpOptions
  185. {
  186. Server = "broker.hivemq.org",
  187. ClientId = "TestClient",
  188. TlsOptions = new MqttClientTlsOptions
  189. {
  190. UseTls = true,
  191. IgnoreCertificateChainErrors = true,
  192. IgnoreCertificateRevocationErrors = true,
  193. AllowUntrustedCertificates = true
  194. }
  195. };
  196. // ----------------------------------
  197. var wsOptions = new MqttClientWebSocketOptions
  198. {
  199. Uri = "broker.hivemq.com:8000/mqtt",
  200. ClientId = "TestClient"
  201. };
  202. await mqttClient.ConnectAsync(wsOptions);
  203. // ----------------------------------
  204. {
  205. var options = new MqttServerOptions();
  206. var mqttServer = new MqttServerFactory().CreateMqttServer(options);
  207. await mqttServer.StartAsync();
  208. Console.WriteLine("Press any key to exit.");
  209. Console.ReadLine();
  210. await mqttServer.StopAsync();
  211. }
  212. // ----------------------------------
  213. {
  214. var options = new MqttServerOptions
  215. {
  216. ConnectionValidator = c =>
  217. {
  218. if (c.ClientId.Length < 10)
  219. {
  220. return MqttConnectReturnCode.ConnectionRefusedIdentifierRejected;
  221. }
  222. if (c.Username != "mySecretUser")
  223. {
  224. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  225. }
  226. if (c.Password != "mySecretPassword")
  227. {
  228. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  229. }
  230. return MqttConnectReturnCode.ConnectionAccepted;
  231. }
  232. };
  233. }
  234. // ----------------------------------
  235. // For UWP apps:
  236. MqttTcpChannel.CustomIgnorableServerCertificateErrorsResolver = o =>
  237. {
  238. if (o.Server == "server_with_revoked_cert")
  239. {
  240. return new[] { ChainValidationResult.Revoked };
  241. }
  242. return new ChainValidationResult[0];
  243. };
  244. }
  245. }
  246. }