Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

271 рядки
9.1 KiB

  1. using MQTTnet.Core;
  2. using MQTTnet.Core.Client;
  3. using MQTTnet.Core.Diagnostics;
  4. using MQTTnet.Core.Packets;
  5. using MQTTnet.Core.Protocol;
  6. using MQTTnet.Core.Server;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Security.Cryptography.X509Certificates;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using Newtonsoft.Json;
  15. namespace MQTTnet.TestApp.NetCore
  16. {
  17. public static class Program
  18. {
  19. public static void Main()
  20. {
  21. Console.WriteLine("MQTTnet - TestApp.NetFramework");
  22. Console.WriteLine("1 = Start client");
  23. Console.WriteLine("2 = Start server");
  24. Console.WriteLine("3 = Start performance test");
  25. Console.WriteLine("4 = Start managed client");
  26. var pressedKey = Console.ReadKey(true);
  27. if (pressedKey.KeyChar == '1')
  28. {
  29. Task.Run(RunClientAsync);
  30. }
  31. else if (pressedKey.KeyChar == '2')
  32. {
  33. Task.Run(RunServerAsync);
  34. }
  35. else if (pressedKey.KeyChar == '3')
  36. {
  37. Task.Run(PerformanceTest.RunAsync);
  38. }
  39. else if (pressedKey.KeyChar == '4')
  40. {
  41. Task.Run(ManagedClientTest.RunAsync);
  42. }
  43. Thread.Sleep(Timeout.Infinite);
  44. }
  45. private static async Task RunClientAsync()
  46. {
  47. MqttNetTrace.TraceMessagePublished += (s, e) =>
  48. {
  49. Console.WriteLine($">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}");
  50. if (e.TraceMessage.Exception != null)
  51. {
  52. Console.WriteLine(e.TraceMessage.Exception);
  53. }
  54. };
  55. try
  56. {
  57. var options = new MqttClientWebSocketOptions
  58. {
  59. Uri = "localhost",
  60. ClientId = "XYZ",
  61. CleanSession = true
  62. };
  63. var client = new MqttClientFactory().CreateMqttClient();
  64. client.ApplicationMessageReceived += (s, e) =>
  65. {
  66. Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
  67. Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
  68. Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
  69. Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
  70. Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
  71. Console.WriteLine();
  72. };
  73. client.Connected += async (s, e) =>
  74. {
  75. Console.WriteLine("### CONNECTED WITH SERVER ###");
  76. await client.SubscribeAsync(new List<TopicFilter>
  77. {
  78. new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
  79. });
  80. Console.WriteLine("### SUBSCRIBED ###");
  81. };
  82. client.Disconnected += async (s, e) =>
  83. {
  84. Console.WriteLine("### DISCONNECTED FROM SERVER ###");
  85. await Task.Delay(TimeSpan.FromSeconds(5));
  86. try
  87. {
  88. await client.ConnectAsync(options);
  89. }
  90. catch
  91. {
  92. Console.WriteLine("### RECONNECTING FAILED ###");
  93. }
  94. };
  95. try
  96. {
  97. await client.ConnectAsync(options);
  98. }
  99. catch (Exception exception)
  100. {
  101. Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
  102. }
  103. Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
  104. while (true)
  105. {
  106. Console.ReadLine();
  107. var applicationMessage = new MqttApplicationMessage(
  108. "A/B/C",
  109. Encoding.UTF8.GetBytes("Hello World"),
  110. MqttQualityOfServiceLevel.AtLeastOnce,
  111. false
  112. );
  113. await client.PublishAsync(applicationMessage);
  114. }
  115. }
  116. catch (Exception exception)
  117. {
  118. Console.WriteLine(exception);
  119. }
  120. }
  121. private static Task RunServerAsync()
  122. {
  123. MqttNetTrace.TraceMessagePublished += (s, e) =>
  124. {
  125. Console.WriteLine($">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}");
  126. if (e.TraceMessage.Exception != null)
  127. {
  128. Console.WriteLine(e.TraceMessage.Exception);
  129. }
  130. };
  131. try
  132. {
  133. var options = new MqttServerOptions
  134. {
  135. ConnectionValidator = p =>
  136. {
  137. if (p.ClientId == "SpecialClient")
  138. {
  139. if (p.Username != "USER" || p.Password != "PASS")
  140. {
  141. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  142. }
  143. }
  144. return MqttConnectReturnCode.ConnectionAccepted;
  145. }
  146. };
  147. options.Storage = new RetainedMessageHandler();
  148. //var certificate = new X509Certificate(@"C:\certs\test\test.cer", "");
  149. //options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
  150. //options.ConnectionBacklog = 5;
  151. //options.DefaultEndpointOptions.IsEnabled = true;
  152. //options.TlsEndpointOptions.IsEnabled = false;
  153. var mqttServer = new MqttServerFactory().CreateMqttServer(options);
  154. mqttServer.ClientDisconnected += (s, e) =>
  155. {
  156. Console.Write("Client disconnected event fired.");
  157. };
  158. mqttServer.StartAsync();
  159. Console.WriteLine("Press any key to exit.");
  160. Console.ReadLine();
  161. mqttServer.StopAsync();
  162. }
  163. catch (Exception e)
  164. {
  165. Console.WriteLine(e);
  166. }
  167. Console.ReadLine();
  168. return Task.FromResult(0);
  169. }
  170. // ReSharper disable once UnusedMember.Local
  171. private static async void WikiCode()
  172. {
  173. {
  174. var client = new MqttClientFactory().CreateMqttClient(new CustomTraceHandler("Client 1"));
  175. var message = new MqttApplicationMessageBuilder()
  176. .WithTopic("MyTopic")
  177. .WithPayload("Hello World")
  178. .WithExactlyOnceQoS()
  179. .WithRetainFlag()
  180. .Build();
  181. await client.PublishAsync(message);
  182. }
  183. {
  184. var message = new MqttApplicationMessageBuilder()
  185. .WithTopic("/MQTTnet/is/awesome")
  186. .Build();
  187. }
  188. }
  189. }
  190. public class CustomTraceHandler : IMqttNetTraceHandler
  191. {
  192. private readonly string _clientId;
  193. public CustomTraceHandler(string clientId)
  194. {
  195. _clientId = clientId;
  196. }
  197. public bool IsEnabled { get; } = true;
  198. public void HandleTraceMessage(MqttNetTraceMessage traceMessage)
  199. {
  200. // Client ID is added to the trace message.
  201. Console.WriteLine($">> [{_clientId}] [{traceMessage.Timestamp:O}] [{traceMessage.ThreadId}] [{traceMessage.Source}] [{traceMessage.Level}]: {traceMessage.Message}");
  202. if (traceMessage.Exception != null)
  203. {
  204. Console.WriteLine(traceMessage.Exception);
  205. }
  206. }
  207. }
  208. public class RetainedMessageHandler : IMqttServerStorage
  209. {
  210. private const string Filename = "C:\\MQTT\\RetainedMessages.json";
  211. public Task SaveRetainedMessagesAsync(IList<MqttApplicationMessage> messages)
  212. {
  213. File.WriteAllText(Filename, JsonConvert.SerializeObject(messages));
  214. return Task.FromResult(0);
  215. }
  216. public Task<IList<MqttApplicationMessage>> LoadRetainedMessagesAsync()
  217. {
  218. IList<MqttApplicationMessage> retainedMessages;
  219. if (File.Exists(Filename))
  220. {
  221. var json = File.ReadAllText(Filename);
  222. retainedMessages = JsonConvert.DeserializeObject<List<MqttApplicationMessage>>(json);
  223. }
  224. else
  225. {
  226. retainedMessages = new List<MqttApplicationMessage>();
  227. }
  228. return Task.FromResult(retainedMessages);
  229. }
  230. }
  231. }