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.
 
 
 
 

98 wiersze
3.4 KiB

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