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.
 
 
 
 

95 lines
3.2 KiB

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