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.
 
 
 
 

111 lines
3.5 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using MQTTnet.Core;
  6. using MQTTnet.Core.Client;
  7. using MQTTnet.Core.Diagnostics;
  8. using MQTTnet.Core.Packets;
  9. using MQTTnet.Core.Protocol;
  10. using MQTTnet.Core.Server;
  11. namespace MQTTnet.TestMqttClient
  12. {
  13. public static class Program
  14. {
  15. public static void Main(string[] arguments)
  16. {
  17. Task.Run(() => Run(arguments)).Wait();
  18. }
  19. private static async Task Run(string[] arguments)
  20. {
  21. MqttTrace.TraceMessagePublished += (s, e) =>
  22. {
  23. Console.WriteLine($">> [{e.ThreadId}] [{e.Source}] [{e.Level}]: {e.Message}");
  24. if (e.Exception != null)
  25. {
  26. Console.WriteLine(e.Exception);
  27. }
  28. };
  29. try
  30. {
  31. var options = new MqttClientOptions
  32. {
  33. Server = "localhost",
  34. ClientId = "XYZ",
  35. CleanSession = true
  36. };
  37. var client = new MqttClientFactory().CreateMqttClient(options);
  38. client.ApplicationMessageReceived += (s, e) =>
  39. {
  40. Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
  41. Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
  42. Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
  43. Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
  44. Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
  45. Console.WriteLine();
  46. };
  47. client.Connected += async (s, e) =>
  48. {
  49. Console.WriteLine("### CONNECTED WITH SERVER ###");
  50. await client.SubscribeAsync(new List<TopicFilter>
  51. {
  52. new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
  53. });
  54. Console.WriteLine("### SUBSCRIBED ###");
  55. };
  56. client.Disconnected += async (s, e) =>
  57. {
  58. Console.WriteLine("### DISCONNECTED FROM SERVER ###");
  59. await Task.Delay(TimeSpan.FromSeconds(5));
  60. try
  61. {
  62. await client.ConnectAsync();
  63. }
  64. catch
  65. {
  66. Console.WriteLine("### RECONNECTING FAILED ###");
  67. }
  68. };
  69. try
  70. {
  71. await client.ConnectAsync();
  72. }
  73. catch
  74. {
  75. Console.WriteLine("### CONNECTING FAILED ###");
  76. }
  77. Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
  78. while (true)
  79. {
  80. Console.ReadLine();
  81. var applicationMessage = new MqttApplicationMessage(
  82. "A/B/C",
  83. Encoding.UTF8.GetBytes("Hello World"),
  84. MqttQualityOfServiceLevel.AtLeastOnce,
  85. false
  86. );
  87. await client.PublishAsync(applicationMessage);
  88. }
  89. }
  90. catch (Exception exception)
  91. {
  92. Console.WriteLine(exception);
  93. }
  94. }
  95. }
  96. }