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.
 
 
 
 

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