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.
 
 
 
 

123 lines
4.8 KiB

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