Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

109 Zeilen
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. };
  35. var client = new MqttClientFactory().CreateMqttClient(options);
  36. client.ApplicationMessageReceived += (s, e) =>
  37. {
  38. Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
  39. Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
  40. Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
  41. Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
  42. Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
  43. Console.WriteLine();
  44. };
  45. client.Connected += async (s, e) =>
  46. {
  47. Console.WriteLine("### CONNECTED WITH SERVER ###");
  48. await client.SubscribeAsync(new List<TopicFilter>
  49. {
  50. new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
  51. });
  52. Console.WriteLine("### SUBSCRIBED ###");
  53. };
  54. client.Disconnected += async (s, e) =>
  55. {
  56. Console.WriteLine("### DISCONNECTED FROM SERVER ###");
  57. await Task.Delay(TimeSpan.FromSeconds(5));
  58. try
  59. {
  60. await client.ConnectAsync();
  61. }
  62. catch
  63. {
  64. Console.WriteLine("### RECONNECTING FAILED ###");
  65. }
  66. };
  67. try
  68. {
  69. await client.ConnectAsync();
  70. }
  71. catch
  72. {
  73. Console.WriteLine("### CONNECTING FAILED ###");
  74. }
  75. Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
  76. while (true)
  77. {
  78. Console.ReadLine();
  79. var applicationMessage = new MqttApplicationMessage(
  80. "A/B/C",
  81. Encoding.UTF8.GetBytes("Hello World"),
  82. MqttQualityOfServiceLevel.AtLeastOnce,
  83. false
  84. );
  85. await client.PublishAsync(applicationMessage);
  86. }
  87. }
  88. catch (Exception exception)
  89. {
  90. Console.WriteLine(exception);
  91. }
  92. }
  93. }
  94. }