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.
 
 
 
 

81 lines
2.9 KiB

  1. using System;
  2. using System.Text;
  3. using System.Threading.Tasks;
  4. using MQTTnet.Core.Protocol;
  5. using MQTTnet.Core.Server;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Extensions.Logging;
  8. namespace MQTTnet.TestApp.NetCore
  9. {
  10. public static class ServerTest
  11. {
  12. public static Task RunAsync()
  13. {
  14. try
  15. {
  16. var services = new ServiceCollection()
  17. .AddMqttServer()
  18. .AddLogging();
  19. services.Configure<MqttServerOptions>(options =>
  20. {
  21. options.ConnectionValidator = p =>
  22. {
  23. if (p.ClientId == "SpecialClient")
  24. {
  25. if (p.Username != "USER" || p.Password != "PASS")
  26. {
  27. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  28. }
  29. }
  30. return MqttConnectReturnCode.ConnectionAccepted;
  31. };
  32. options.Storage = new RetainedMessageHandler();
  33. options.ApplicationMessageInterceptor = context =>
  34. {
  35. if (MqttTopicFilterComparer.IsMatch(context.ApplicationMessage.Topic, "/myTopic/WithTimestamp/#"))
  36. {
  37. // Replace the payload with the timestamp. But also extending a JSON
  38. // based payload with the timestamp is a suitable use case.
  39. context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O"));
  40. }
  41. };
  42. });
  43. var serviceProvider = services.BuildServiceProvider();
  44. serviceProvider.GetRequiredService<ILoggerFactory>().AddConsole();
  45. //var certificate = new X509Certificate(@"C:\certs\test\test.cer", "");
  46. //options.TlsEndpointOptions.Certificate = certificate.Export(X509ContentType.Cert);
  47. //options.ConnectionBacklog = 5;
  48. //options.DefaultEndpointOptions.IsEnabled = true;
  49. //options.TlsEndpointOptions.IsEnabled = false;
  50. var mqttServer = new MqttFactory(serviceProvider).CreateMqttServer();
  51. mqttServer.ClientDisconnected += (s, e) =>
  52. {
  53. Console.Write("Client disconnected event fired.");
  54. };
  55. mqttServer.StartAsync();
  56. Console.WriteLine("Press any key to exit.");
  57. Console.ReadLine();
  58. mqttServer.StopAsync();
  59. }
  60. catch (Exception e)
  61. {
  62. Console.WriteLine(e);
  63. }
  64. Console.ReadLine();
  65. return Task.FromResult(0);
  66. }
  67. }
  68. }