Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

98 lignes
3.4 KiB

  1. using System;
  2. using System.Text;
  3. using System.Threading.Tasks;
  4. using MQTTnet.Client;
  5. using MQTTnet.Client.Connecting;
  6. using MQTTnet.Client.Disconnecting;
  7. using MQTTnet.Client.Options;
  8. using MQTTnet.Client.Receiving;
  9. using MQTTnet.Protocol;
  10. namespace MQTTnet.TestApp.NetCore
  11. {
  12. public static class ClientTest
  13. {
  14. public static async Task RunAsync()
  15. {
  16. try
  17. {
  18. MqttNetConsoleLogger.ForwardToConsole();
  19. var factory = new MqttFactory();
  20. var client = factory.CreateMqttClient();
  21. var clientOptions = new MqttClientOptions
  22. {
  23. ChannelOptions = new MqttClientTcpOptions
  24. {
  25. Server = "127.0.0.1"
  26. }
  27. };
  28. client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
  29. {
  30. Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
  31. Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
  32. Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
  33. Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
  34. Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
  35. Console.WriteLine();
  36. });
  37. client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(async e =>
  38. {
  39. Console.WriteLine("### CONNECTED WITH SERVER ###");
  40. await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build());
  41. Console.WriteLine("### SUBSCRIBED ###");
  42. });
  43. client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async e =>
  44. {
  45. Console.WriteLine("### DISCONNECTED FROM SERVER ###");
  46. await Task.Delay(TimeSpan.FromSeconds(5));
  47. try
  48. {
  49. await client.ConnectAsync(clientOptions);
  50. }
  51. catch
  52. {
  53. Console.WriteLine("### RECONNECTING FAILED ###");
  54. }
  55. });
  56. try
  57. {
  58. await client.ConnectAsync(clientOptions);
  59. }
  60. catch (Exception exception)
  61. {
  62. Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
  63. }
  64. Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
  65. while (true)
  66. {
  67. Console.ReadLine();
  68. await client.SubscribeAsync(new TopicFilter { Topic = "test", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce });
  69. var applicationMessage = new MqttApplicationMessageBuilder()
  70. .WithTopic("A/B/C")
  71. .WithPayload("Hello World")
  72. .WithAtLeastOnceQoS()
  73. .Build();
  74. await client.PublishAsync(applicationMessage);
  75. }
  76. }
  77. catch (Exception exception)
  78. {
  79. Console.WriteLine(exception);
  80. }
  81. }
  82. }
  83. }