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.
 
 
 
 

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