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.
 
 
 
 

148 line
5.9 KiB

  1. using System;
  2. using System.Text;
  3. using System.Threading.Tasks;
  4. using MQTTnet.Client.Receiving;
  5. using MQTTnet.Diagnostics;
  6. using MQTTnet.Diagnostics.Logger;
  7. using MQTTnet.Protocol;
  8. using MQTTnet.Server;
  9. using MQTTnet.Server.Internal;
  10. namespace MQTTnet.TestApp.NetCore
  11. {
  12. public static class ServerTest
  13. {
  14. public static void RunEmptyServer()
  15. {
  16. var mqttServer = new MqttFactory().CreateMqttServer();
  17. mqttServer.StartAsync(new MqttServerOptions()).GetAwaiter().GetResult();
  18. Console.WriteLine("Press any key to exit.");
  19. Console.ReadLine();
  20. }
  21. public static void RunEmptyServerWithLogging()
  22. {
  23. var logger = new MqttNetEventLogger();
  24. MqttNetConsoleLogger.ForwardToConsole(logger);
  25. var mqttFactory = new MqttFactory(logger);
  26. var mqttServer = mqttFactory.CreateMqttServer();
  27. mqttServer.StartAsync(new MqttServerOptions()).GetAwaiter().GetResult();
  28. Console.WriteLine("Press any key to exit.");
  29. Console.ReadLine();
  30. }
  31. public static async Task RunAsync()
  32. {
  33. try
  34. {
  35. var options = new MqttServerOptions
  36. {
  37. ConnectionValidator = new MqttServerConnectionValidatorDelegate(p =>
  38. {
  39. if (p.ClientId == "SpecialClient")
  40. {
  41. if (p.Username != "USER" || p.Password != "PASS")
  42. {
  43. p.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
  44. }
  45. }
  46. }),
  47. Storage = new RetainedMessageHandler(),
  48. ApplicationMessageInterceptor = new MqttServerApplicationMessageInterceptorDelegate(context =>
  49. {
  50. if (MqttTopicFilterComparer.IsMatch(context.ApplicationMessage.Topic, "/myTopic/WithTimestamp/#"))
  51. {
  52. // Replace the payload with the timestamp. But also extending a JSON
  53. // based payload with the timestamp is a suitable use case.
  54. context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O"));
  55. }
  56. if (context.ApplicationMessage.Topic == "not_allowed_topic")
  57. {
  58. context.AcceptPublish = false;
  59. context.CloseConnection = true;
  60. }
  61. }),
  62. SubscriptionInterceptor = new MqttServerSubscriptionInterceptorDelegate(context =>
  63. {
  64. if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin")
  65. {
  66. context.AcceptSubscription = false;
  67. }
  68. if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator")
  69. {
  70. context.AcceptSubscription = false;
  71. context.CloseConnection = true;
  72. }
  73. })
  74. };
  75. // Extend the timestamp for all messages from clients.
  76. // Protect several topics from being subscribed from every client.
  77. //var certificate = new X509Certificate(@"C:\certs\test\test.cer", "");
  78. //options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
  79. //options.ConnectionBacklog = 5;
  80. //options.DefaultEndpointOptions.IsEnabled = true;
  81. //options.TlsEndpointOptions.IsEnabled = false;
  82. var mqttServer = new MqttFactory().CreateMqttServer();
  83. mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
  84. {
  85. MqttNetConsoleLogger.PrintToConsole(
  86. $"'{e.ClientId}' reported '{e.ApplicationMessage.Topic}' > '{Encoding.UTF8.GetString(e.ApplicationMessage.Payload ?? new byte[0])}'",
  87. ConsoleColor.Magenta);
  88. });
  89. //options.ApplicationMessageInterceptor = c =>
  90. //{
  91. // if (c.ApplicationMessage.Payload == null || c.ApplicationMessage.Payload.Length == 0)
  92. // {
  93. // return;
  94. // }
  95. // try
  96. // {
  97. // var content = JObject.Parse(Encoding.UTF8.GetString(c.ApplicationMessage.Payload));
  98. // var timestampProperty = content.Property("timestamp");
  99. // if (timestampProperty != null && timestampProperty.Value.Type == JTokenType.Null)
  100. // {
  101. // timestampProperty.Value = DateTime.Now.ToString("O");
  102. // c.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(content.ToString());
  103. // }
  104. // }
  105. // catch (Exception)
  106. // {
  107. // }
  108. //};
  109. mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(e =>
  110. {
  111. Console.Write("Client disconnected event fired.");
  112. });
  113. await mqttServer.StartAsync(options);
  114. Console.WriteLine("Press any key to exit.");
  115. Console.ReadLine();
  116. await mqttServer.StopAsync();
  117. }
  118. catch (Exception e)
  119. {
  120. Console.WriteLine(e);
  121. }
  122. Console.ReadLine();
  123. }
  124. }
  125. }