Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

ClientTest.cs 3.4 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. var options = new MqttClientOptions
  15. {
  16. ClientId = "XYZ",
  17. CleanSession = true,
  18. ChannelOptions = new MqttClientTcpOptions
  19. {
  20. //Server = "localhost",
  21. Server = "192.168.1.174"
  22. },
  23. //ChannelOptions = new MqttClientWebSocketOptions
  24. //{
  25. // Uri = "ws://localhost:59690/mqtt"
  26. //}
  27. };
  28. var factory = new MqttFactory();
  29. var client = factory.CreateMqttClient();
  30. client.ApplicationMessageReceived += (s, e) =>
  31. {
  32. Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
  33. Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
  34. Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
  35. Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
  36. Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
  37. Console.WriteLine();
  38. };
  39. client.Connected += async (s, e) =>
  40. {
  41. Console.WriteLine("### CONNECTED WITH SERVER ###");
  42. await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build());
  43. Console.WriteLine("### SUBSCRIBED ###");
  44. };
  45. client.Disconnected += async (s, e) =>
  46. {
  47. Console.WriteLine("### DISCONNECTED FROM SERVER ###");
  48. await Task.Delay(TimeSpan.FromSeconds(5));
  49. try
  50. {
  51. await client.ConnectAsync(options);
  52. }
  53. catch
  54. {
  55. Console.WriteLine("### RECONNECTING FAILED ###");
  56. }
  57. };
  58. try
  59. {
  60. await client.ConnectAsync(options);
  61. }
  62. catch (Exception exception)
  63. {
  64. Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
  65. }
  66. Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
  67. while (true)
  68. {
  69. Console.ReadLine();
  70. await client.SubscribeAsync(new TopicFilter("test", MqttQualityOfServiceLevel.AtMostOnce));
  71. var applicationMessage = new MqttApplicationMessageBuilder()
  72. .WithTopic("A/B/C")
  73. .WithPayload("Hello World")
  74. .WithAtLeastOnceQoS()
  75. .Build();
  76. await client.PublishAsync(applicationMessage);
  77. }
  78. }
  79. catch (Exception exception)
  80. {
  81. Console.WriteLine(exception);
  82. }
  83. }
  84. }
  85. }