Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

64 righe
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. }