Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Program.cs 7.0 KiB

il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. }