您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

132 行
5.3 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. if (p.Username != "USER" || p.Password != "PASS")
  29. {
  30. p.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
  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. }