Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ClientTest.cs 3.1 KiB

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