您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

113 行
3.7 KiB

  1. using System;
  2. using System.Threading.Tasks;
  3. using MQTTnet.Core;
  4. using MQTTnet.Core.Client;
  5. using MQTTnet.Core.ManagedClient;
  6. using MQTTnet.Core.Protocol;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Microsoft.Extensions.Logging;
  9. using System.IO;
  10. using Newtonsoft.Json;
  11. using System.Collections.Generic;
  12. namespace MQTTnet.TestApp.NetCore
  13. {
  14. public static class ManagedClientTest
  15. {
  16. public static async Task RunAsync()
  17. {
  18. var services = new ServiceCollection()
  19. .AddMqttClient()
  20. .AddLogging()
  21. .BuildServiceProvider();
  22. services.GetService<ILoggerFactory>()
  23. .AddConsole();
  24. var ms = new ClientRetainedMessageHandler();
  25. var options = new ManagedMqttClientOptions
  26. {
  27. ClientOptions = new MqttClientOptions
  28. {
  29. ClientId = "MQTTnetManagedClientTest",
  30. Credentials = new RandomPassword(),
  31. ChannelOptions = new MqttClientTcpOptions
  32. {
  33. Server = "broker.hivemq.com"
  34. }
  35. },
  36. AutoReconnectDelay = TimeSpan.FromSeconds(1),
  37. Storage = ms
  38. };
  39. try
  40. {
  41. var managedClient = services.GetRequiredService<ManagedMqttClient>();
  42. managedClient.ApplicationMessageReceived += (s, e) =>
  43. {
  44. Console.WriteLine(">> RECEIVED: " + e.ApplicationMessage.Topic);
  45. };
  46. await managedClient.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("Step").WithPayload("1").Build());
  47. await managedClient.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("Step").WithPayload("2").WithAtLeastOnceQoS().Build());
  48. await managedClient.StartAsync(options);
  49. await managedClient.SubscribeAsync(new TopicFilter("xyz", MqttQualityOfServiceLevel.AtMostOnce));
  50. await managedClient.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("Step").WithPayload("3").Build());
  51. Console.WriteLine("Managed client started.");
  52. Console.ReadLine();
  53. }
  54. catch (Exception e)
  55. {
  56. Console.WriteLine(e);
  57. }
  58. }
  59. public class RandomPassword : IMqttClientCredentials
  60. {
  61. public string Password
  62. {
  63. get
  64. {
  65. return Guid.NewGuid().ToString(); // The random password.
  66. }
  67. }
  68. public string Username => "the_static_user";
  69. }
  70. public class ClientRetainedMessageHandler : IManagedMqttClientStorage
  71. {
  72. private const string Filename = @"RetainedMessages.json";
  73. public Task SaveQueuedMessagesAsync(IList<MqttApplicationMessage> messages)
  74. {
  75. File.WriteAllText(Filename, JsonConvert.SerializeObject(messages));
  76. return Task.FromResult(0);
  77. }
  78. public Task<IList<MqttApplicationMessage>> LoadQueuedMessagesAsync()
  79. {
  80. IList<MqttApplicationMessage> retainedMessages;
  81. if (File.Exists(Filename))
  82. {
  83. var json = File.ReadAllText(Filename);
  84. retainedMessages = JsonConvert.DeserializeObject<List<MqttApplicationMessage>>(json);
  85. }
  86. else
  87. {
  88. retainedMessages = new List<MqttApplicationMessage>();
  89. }
  90. return Task.FromResult(retainedMessages);
  91. }
  92. }
  93. }
  94. }