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.
 
 
 
 

133 line
5.4 KiB

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