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.
 
 
 
 

84 line
2.9 KiB

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