25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

ServerTest.cs 5.2 KiB

7 yıl önce
7 yıl önce
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. }