You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

194 lines
6.3 KiB

  1. using MQTTnet.Core;
  2. using MQTTnet.Core.Client;
  3. using MQTTnet.Core.Packets;
  4. using MQTTnet.Core.Protocol;
  5. using MQTTnet.Core.Server;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Security.Cryptography.X509Certificates;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using Newtonsoft.Json;
  14. using Microsoft.Extensions.DependencyInjection;
  15. using Microsoft.Extensions.Logging;
  16. namespace MQTTnet.TestApp.NetCore
  17. {
  18. public static class Program
  19. {
  20. public static void Main()
  21. {
  22. Console.WriteLine("MQTTnet - TestApp.NetFramework");
  23. Console.WriteLine("1 = Start client");
  24. Console.WriteLine("2 = Start server");
  25. Console.WriteLine("3 = Start performance test");
  26. Console.WriteLine("4 = Start managed client");
  27. var pressedKey = Console.ReadKey(true);
  28. if (pressedKey.KeyChar == '1')
  29. {
  30. Task.Run(RunClientAsync);
  31. }
  32. else if (pressedKey.KeyChar == '2')
  33. {
  34. Task.Run(ServerTest.RunAsync);
  35. }
  36. else if (pressedKey.KeyChar == '3')
  37. {
  38. Task.Run(PerformanceTest.RunAsync);
  39. }
  40. else if (pressedKey.KeyChar == '4')
  41. {
  42. Task.Run(ManagedClientTest.RunAsync);
  43. }
  44. Thread.Sleep(Timeout.Infinite);
  45. }
  46. private static async Task RunClientAsync()
  47. {
  48. try
  49. {
  50. var services = new ServiceCollection()
  51. .AddMqttServer()
  52. .AddLogging()
  53. .BuildServiceProvider();
  54. services.GetService<ILoggerFactory>()
  55. .AddConsole();
  56. var options = new MqttClientWebSocketOptions
  57. {
  58. Uri = "localhost",
  59. ClientId = "XYZ",
  60. CleanSession = true
  61. };
  62. var client = services.GetRequiredService<IMqttClient>();
  63. client.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. client.Connected += async (s, e) =>
  73. {
  74. Console.WriteLine("### CONNECTED WITH SERVER ###");
  75. await client.SubscribeAsync(new List<TopicFilter>
  76. {
  77. new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
  78. });
  79. Console.WriteLine("### SUBSCRIBED ###");
  80. };
  81. client.Disconnected += async (s, e) =>
  82. {
  83. Console.WriteLine("### DISCONNECTED FROM SERVER ###");
  84. await Task.Delay(TimeSpan.FromSeconds(5));
  85. try
  86. {
  87. await client.ConnectAsync(options);
  88. }
  89. catch
  90. {
  91. Console.WriteLine("### RECONNECTING FAILED ###");
  92. }
  93. };
  94. try
  95. {
  96. await client.ConnectAsync(options);
  97. }
  98. catch (Exception exception)
  99. {
  100. Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
  101. }
  102. Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
  103. while (true)
  104. {
  105. Console.ReadLine();
  106. var applicationMessage = new MqttApplicationMessage
  107. {
  108. Topic = "A/B/C",
  109. Payload = Encoding.UTF8.GetBytes("Hello World"),
  110. QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce
  111. };
  112. await client.PublishAsync(applicationMessage);
  113. }
  114. }
  115. catch (Exception exception)
  116. {
  117. Console.WriteLine(exception);
  118. }
  119. }
  120. // ReSharper disable once UnusedMember.Local
  121. private static async void WikiCode()
  122. {
  123. {
  124. var serviceProvider = new ServiceCollection()
  125. .AddMqttServer()
  126. .AddLogging()
  127. .BuildServiceProvider();
  128. var client = serviceProvider.GetRequiredService<IMqttClient>();
  129. var message = new MqttApplicationMessageBuilder()
  130. .WithTopic("MyTopic")
  131. .WithPayload("Hello World")
  132. .WithExactlyOnceQoS()
  133. .WithRetainFlag()
  134. .Build();
  135. await client.PublishAsync(message);
  136. }
  137. {
  138. var message = new MqttApplicationMessageBuilder()
  139. .WithTopic("/MQTTnet/is/awesome")
  140. .Build();
  141. }
  142. }
  143. }
  144. public class RetainedMessageHandler : IMqttServerStorage
  145. {
  146. private const string Filename = "C:\\MQTT\\RetainedMessages.json";
  147. public Task SaveRetainedMessagesAsync(IList<MqttApplicationMessage> messages)
  148. {
  149. File.WriteAllText(Filename, JsonConvert.SerializeObject(messages));
  150. return Task.FromResult(0);
  151. }
  152. public Task<IList<MqttApplicationMessage>> LoadRetainedMessagesAsync()
  153. {
  154. IList<MqttApplicationMessage> retainedMessages;
  155. if (File.Exists(Filename))
  156. {
  157. var json = File.ReadAllText(Filename);
  158. retainedMessages = JsonConvert.DeserializeObject<List<MqttApplicationMessage>>(json);
  159. }
  160. else
  161. {
  162. retainedMessages = new List<MqttApplicationMessage>();
  163. }
  164. return Task.FromResult(retainedMessages);
  165. }
  166. }
  167. }