Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

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