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.
 
 
 
 

103 linhas
3.5 KiB

  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using MQTTnet.Client;
  5. using System;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using MQTTnet.Diagnostics;
  9. using MQTTnet.Implementations;
  10. using MQTTnet.Protocol;
  11. namespace MQTTnet.TestApp
  12. {
  13. public static class ClientTest
  14. {
  15. public static async Task RunAsync()
  16. {
  17. try
  18. {
  19. var logger = new MqttNetEventLogger();
  20. MqttNetConsoleLogger.ForwardToConsole(logger);
  21. var factory = new MqttFactory(logger);
  22. var client = factory.CreateMqttClient();
  23. var clientOptions = new MqttClientOptions
  24. {
  25. ChannelOptions = new MqttClientTcpOptions
  26. {
  27. Server = "127.0.0.1"
  28. }
  29. };
  30. client.ApplicationMessageReceivedAsync += e =>
  31. {
  32. Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
  33. Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
  34. Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
  35. Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
  36. Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
  37. Console.WriteLine();
  38. return PlatformAbstractionLayer.CompletedTask;
  39. };
  40. client.ConnectedAsync += async e =>
  41. {
  42. Console.WriteLine("### CONNECTED WITH SERVER ###");
  43. await client.SubscribeAsync("#");
  44. Console.WriteLine("### SUBSCRIBED ###");
  45. };
  46. client.DisconnectedAsync += async e =>
  47. {
  48. Console.WriteLine("### DISCONNECTED FROM SERVER ###");
  49. await Task.Delay(TimeSpan.FromSeconds(5));
  50. try
  51. {
  52. await client.ConnectAsync(clientOptions);
  53. }
  54. catch
  55. {
  56. Console.WriteLine("### RECONNECTING FAILED ###");
  57. }
  58. };
  59. try
  60. {
  61. await client.ConnectAsync(clientOptions);
  62. }
  63. catch (Exception exception)
  64. {
  65. Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
  66. }
  67. Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
  68. while (true)
  69. {
  70. Console.ReadLine();
  71. await client.SubscribeAsync("test");
  72. var applicationMessage = new MqttApplicationMessageBuilder()
  73. .WithTopic("A/B/C")
  74. .WithPayload("Hello World")
  75. .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
  76. .Build();
  77. await client.PublishAsync(applicationMessage);
  78. }
  79. }
  80. catch (Exception exception)
  81. {
  82. Console.WriteLine(exception);
  83. }
  84. }
  85. }
  86. }