25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

189 lines
6.4 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MQTTnet.Core;
  7. using MQTTnet.Core.Client;
  8. using MQTTnet.Core.Diagnostics;
  9. using MQTTnet.Core.Packets;
  10. using MQTTnet.Core.Protocol;
  11. using MQTTnet.Core.Server;
  12. using MQTTnet.Implementations;
  13. namespace MQTTnet.TestApp.NetFramework
  14. {
  15. public static class Program
  16. {
  17. public static void Main(string[] args)
  18. {
  19. Console.WriteLine("MQTTnet - TestApp.NetFramework");
  20. Console.WriteLine("1 = Start client");
  21. Console.WriteLine("2 = Start server");
  22. Console.WriteLine("3 = Start performance test");
  23. var pressedKey = Console.ReadKey(true);
  24. if (pressedKey.Key == ConsoleKey.D1)
  25. {
  26. Task.Run(() => RunClientAsync(args));
  27. Thread.Sleep(Timeout.Infinite);
  28. }
  29. else if (pressedKey.Key == ConsoleKey.D2)
  30. {
  31. Task.Run(() => RunServerAsync(args));
  32. Thread.Sleep(Timeout.Infinite);
  33. }
  34. else if (pressedKey.Key == ConsoleKey.D3)
  35. {
  36. Task.Run(PerformanceTest.RunAsync);
  37. Thread.Sleep(Timeout.Infinite);
  38. }
  39. }
  40. private static async Task RunClientAsync(string[] arguments)
  41. {
  42. MqttNetTrace.TraceMessagePublished += (s, e) =>
  43. {
  44. Console.WriteLine($">> [{e.ThreadId}] [{e.Source}] [{e.Level}]: {e.Message}");
  45. if (e.Exception != null)
  46. {
  47. Console.WriteLine(e.Exception);
  48. }
  49. };
  50. try
  51. {
  52. var options = new MqttClientWebSocketOptions
  53. {
  54. Uri = "broker.hivemq.com:8000/mqtt"
  55. };
  56. ////var options = new MqttClientOptions
  57. ////{
  58. //// Server = "localhost",
  59. //// ClientId = "XYZ",
  60. //// CleanSession = true
  61. ////};
  62. var mqttClient = new MqttClientFactory().CreateMqttClient();
  63. mqttClient.ApplicationMessageReceived += (s, e) =>
  64. {
  65. Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
  66. Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
  67. Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
  68. Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
  69. Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
  70. Console.WriteLine();
  71. };
  72. mqttClient.Connected += async (s, e) =>
  73. {
  74. Console.WriteLine("### CONNECTED WITH SERVER ###");
  75. await mqttClient.SubscribeAsync(new List<TopicFilter>
  76. {
  77. new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
  78. });
  79. };
  80. mqttClient.Disconnected += async (s, e) =>
  81. {
  82. Console.WriteLine("### DISCONNECTED FROM SERVER ###");
  83. await Task.Delay(TimeSpan.FromSeconds(5));
  84. try
  85. {
  86. await mqttClient.ConnectAsync(options);
  87. }
  88. catch
  89. {
  90. Console.WriteLine("### RECONNECTING FAILED ###");
  91. }
  92. };
  93. try
  94. {
  95. await mqttClient.ConnectAsync(options);
  96. }
  97. catch (Exception exception)
  98. {
  99. Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
  100. }
  101. Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
  102. var messageFactory = new MqttApplicationMessageFactory();
  103. while (true)
  104. {
  105. Console.ReadLine();
  106. var applicationMessage = messageFactory.CreateApplicationMessage("myTopic", "Hello World", MqttQualityOfServiceLevel.AtLeastOnce);
  107. await mqttClient.PublishAsync(applicationMessage);
  108. }
  109. }
  110. catch (Exception exception)
  111. {
  112. Console.WriteLine(exception);
  113. }
  114. }
  115. private static async Task RunServerAsync(string[] arguments)
  116. {
  117. MqttNetTrace.TraceMessagePublished += (s, e) =>
  118. {
  119. Console.WriteLine($">> [{e.ThreadId}] [{e.Source}] [{e.Level}]: {e.Message}");
  120. if (e.Exception != null)
  121. {
  122. Console.WriteLine(e.Exception);
  123. }
  124. };
  125. try
  126. {
  127. var options = new MqttServerOptions
  128. {
  129. ConnectionValidator = p =>
  130. {
  131. if (p.ClientId == "SpecialClient")
  132. {
  133. if (p.Username != "USER" || p.Password != "PASS")
  134. {
  135. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  136. }
  137. }
  138. return MqttConnectReturnCode.ConnectionAccepted;
  139. }
  140. };
  141. var mqttServer = new MqttServerFactory().CreateMqttServer(options);
  142. await mqttServer.StartAsync();
  143. Console.WriteLine("Press any key to exit.");
  144. Console.ReadLine();
  145. await mqttServer.StopAsync();
  146. }
  147. catch (Exception e)
  148. {
  149. Console.WriteLine(e);
  150. }
  151. Console.ReadLine();
  152. }
  153. private static async Task WikiCode()
  154. {
  155. // For .NET Framwork & netstandard apps:
  156. MqttTcpChannel.CustomCertificateValidationCallback = (x509Certificate, x509Chain, sslPolicyErrors, mqttClientTcpOptions) =>
  157. {
  158. if (mqttClientTcpOptions.Server == "server_with_revoked_cert")
  159. {
  160. return true;
  161. }
  162. return false;
  163. };
  164. }
  165. }
  166. }