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.
 
 
 
 

172 lines
5.6 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 MqttClientOptions
  46. {
  47. Server = "localhost",
  48. ClientId = "XYZ",
  49. CleanSession = true,
  50. ConnectionType = MqttConnectionType.Ws
  51. };
  52. var client = new MqttClientFactory().CreateMqttClient(options);
  53. client.ApplicationMessageReceived += (s, e) =>
  54. {
  55. Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
  56. Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
  57. Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
  58. Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
  59. Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
  60. Console.WriteLine();
  61. };
  62. client.Connected += async (s, e) =>
  63. {
  64. Console.WriteLine("### CONNECTED WITH SERVER ###");
  65. await client.SubscribeAsync(new List<TopicFilter>
  66. {
  67. new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
  68. });
  69. Console.WriteLine("### SUBSCRIBED ###");
  70. };
  71. client.Disconnected += async (s, e) =>
  72. {
  73. Console.WriteLine("### DISCONNECTED FROM SERVER ###");
  74. await Task.Delay(TimeSpan.FromSeconds(5));
  75. try
  76. {
  77. await client.ConnectAsync();
  78. }
  79. catch
  80. {
  81. Console.WriteLine("### RECONNECTING FAILED ###");
  82. }
  83. };
  84. try
  85. {
  86. await client.ConnectAsync();
  87. }
  88. catch (Exception exception)
  89. {
  90. Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
  91. }
  92. Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
  93. while (true)
  94. {
  95. Console.ReadLine();
  96. var applicationMessage = new MqttApplicationMessage(
  97. "A/B/C",
  98. Encoding.UTF8.GetBytes("Hello World"),
  99. MqttQualityOfServiceLevel.AtLeastOnce,
  100. false
  101. );
  102. await client.PublishAsync(applicationMessage);
  103. }
  104. }
  105. catch (Exception exception)
  106. {
  107. Console.WriteLine(exception);
  108. }
  109. }
  110. private static void RunServerAsync(string[] arguments)
  111. {
  112. MqttTrace.TraceMessagePublished += (s, e) =>
  113. {
  114. Console.WriteLine($">> [{e.ThreadId}] [{e.Source}] [{e.Level}]: {e.Message}");
  115. if (e.Exception != null)
  116. {
  117. Console.WriteLine(e.Exception);
  118. }
  119. };
  120. try
  121. {
  122. var options = new MqttServerOptions
  123. {
  124. ConnectionValidator = p =>
  125. {
  126. if (p.ClientId == "SpecialClient")
  127. {
  128. if (p.Username != "USER" || p.Password != "PASS")
  129. {
  130. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  131. }
  132. }
  133. return MqttConnectReturnCode.ConnectionAccepted;
  134. }
  135. };
  136. var mqttServer = new MqttServerFactory().CreateMqttServer(options);
  137. mqttServer.Start();
  138. Console.WriteLine("Press any key to exit.");
  139. Console.ReadLine();
  140. mqttServer.Stop();
  141. }
  142. catch (Exception e)
  143. {
  144. Console.WriteLine(e);
  145. }
  146. Console.ReadLine();
  147. }
  148. }
  149. }