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.
 
 
 
 

211 rader
7.0 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(ServerTest.RunAsync);
  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. {
  109. Topic = "A/B/C",
  110. Payload = Encoding.UTF8.GetBytes("Hello World"),
  111. QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce
  112. };
  113. await client.PublishAsync(applicationMessage);
  114. }
  115. }
  116. catch (Exception exception)
  117. {
  118. Console.WriteLine(exception);
  119. }
  120. }
  121. // ReSharper disable once UnusedMember.Local
  122. private static async void WikiCode()
  123. {
  124. {
  125. var client = new MqttClientFactory().CreateMqttClient(new CustomTraceHandler("Client 1"));
  126. var message = new MqttApplicationMessageBuilder()
  127. .WithTopic("MyTopic")
  128. .WithPayload("Hello World")
  129. .WithExactlyOnceQoS()
  130. .WithRetainFlag()
  131. .Build();
  132. await client.PublishAsync(message);
  133. }
  134. {
  135. var message = new MqttApplicationMessageBuilder()
  136. .WithTopic("/MQTTnet/is/awesome")
  137. .Build();
  138. }
  139. }
  140. }
  141. public class CustomTraceHandler : IMqttNetTraceHandler
  142. {
  143. private readonly string _clientId;
  144. public CustomTraceHandler(string clientId)
  145. {
  146. _clientId = clientId;
  147. }
  148. public bool IsEnabled { get; } = true;
  149. public void HandleTraceMessage(MqttNetTraceMessage traceMessage)
  150. {
  151. // Client ID is added to the trace message.
  152. Console.WriteLine($">> [{_clientId}] [{traceMessage.Timestamp:O}] [{traceMessage.ThreadId}] [{traceMessage.Source}] [{traceMessage.Level}]: {traceMessage.Message}");
  153. if (traceMessage.Exception != null)
  154. {
  155. Console.WriteLine(traceMessage.Exception);
  156. }
  157. }
  158. }
  159. public class RetainedMessageHandler : IMqttServerStorage
  160. {
  161. private const string Filename = "C:\\MQTT\\RetainedMessages.json";
  162. public Task SaveRetainedMessagesAsync(IList<MqttApplicationMessage> messages)
  163. {
  164. File.WriteAllText(Filename, JsonConvert.SerializeObject(messages));
  165. return Task.FromResult(0);
  166. }
  167. public Task<IList<MqttApplicationMessage>> LoadRetainedMessagesAsync()
  168. {
  169. IList<MqttApplicationMessage> retainedMessages;
  170. if (File.Exists(Filename))
  171. {
  172. var json = File.ReadAllText(Filename);
  173. retainedMessages = JsonConvert.DeserializeObject<List<MqttApplicationMessage>>(json);
  174. }
  175. else
  176. {
  177. retainedMessages = new List<MqttApplicationMessage>();
  178. }
  179. return Task.FromResult(retainedMessages);
  180. }
  181. }
  182. }