Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

106 righe
4.2 KiB

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