Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

ServerTest.cs 5.3 KiB

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