Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

64 linhas
2.1 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.Packets;
  7. using MQTTnet.Core.Protocol;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.Extensions.Logging;
  10. namespace MQTTnet.TestApp.NetCore
  11. {
  12. public static class ManagedClientTest
  13. {
  14. public static async Task RunAsync()
  15. {
  16. var services = new ServiceCollection()
  17. .AddMqttClient()
  18. .AddLogging()
  19. .BuildServiceProvider();
  20. services.GetService<ILoggerFactory>()
  21. .AddConsole();
  22. var options = new ManagedMqttClientOptions
  23. {
  24. ClientOptions = new MqttClientTcpOptions
  25. {
  26. Server = "broker.hivemq.com",
  27. ClientId = "MQTTnetManagedClientTest"
  28. },
  29. AutoReconnectDelay = TimeSpan.FromSeconds(1)
  30. };
  31. try
  32. {
  33. var managedClient = services.GetRequiredService<ManagedMqttClient>();
  34. managedClient.ApplicationMessageReceived += (s, e) =>
  35. {
  36. Console.WriteLine(">> RECEIVED: " + e.ApplicationMessage.Topic);
  37. };
  38. await managedClient.EnqueueAsync(new MqttApplicationMessageBuilder().WithTopic("Step").WithPayload("1").Build());
  39. await managedClient.EnqueueAsync(new MqttApplicationMessageBuilder().WithTopic("Step").WithPayload("2").WithAtLeastOnceQoS().Build());
  40. await managedClient.StartAsync(options);
  41. await managedClient.SubscribeAsync(new TopicFilter("xyz", MqttQualityOfServiceLevel.AtMostOnce));
  42. await managedClient.EnqueueAsync(new MqttApplicationMessageBuilder().WithTopic("Step").WithPayload("3").Build());
  43. Console.WriteLine("Managed client started.");
  44. Console.ReadLine();
  45. }
  46. catch (Exception e)
  47. {
  48. Console.WriteLine(e);
  49. }
  50. }
  51. }
  52. }