You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

100 rivejä
3.3 KiB

  1. using System;
  2. using System.Text;
  3. using System.Threading.Tasks;
  4. using Microsoft.Extensions.Logging;
  5. using MQTTnet.Core;
  6. using MQTTnet.Core.Client;
  7. namespace MQTTnet.TestApp.NetCore
  8. {
  9. public static class ClientTest
  10. {
  11. public static async Task RunAsync()
  12. {
  13. try
  14. {
  15. var options = new MqttClientOptions
  16. {
  17. ClientId = "XYZ",
  18. CleanSession = true,
  19. ChannelOptions = new MqttClientTcpOptions
  20. {
  21. Server = "localhost"
  22. },
  23. //ChannelOptions = new MqttClientWebSocketOptions
  24. //{
  25. // Uri = "ws://localhost:59690/mqtt"
  26. //}
  27. };
  28. var factory = new MqttFactory();
  29. factory.GetLoggerFactory().AddConsole();
  30. var client = factory.CreateMqttClient();
  31. client.ApplicationMessageReceived += (s, e) =>
  32. {
  33. Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
  34. Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
  35. Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
  36. Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
  37. Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
  38. Console.WriteLine();
  39. };
  40. client.Connected += async (s, e) =>
  41. {
  42. Console.WriteLine("### CONNECTED WITH SERVER ###");
  43. await client.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build());
  44. Console.WriteLine("### SUBSCRIBED ###");
  45. };
  46. client.Disconnected += async (s, e) =>
  47. {
  48. Console.WriteLine("### DISCONNECTED FROM SERVER ###");
  49. await Task.Delay(TimeSpan.FromSeconds(5));
  50. try
  51. {
  52. await client.ConnectAsync(options);
  53. }
  54. catch
  55. {
  56. Console.WriteLine("### RECONNECTING FAILED ###");
  57. }
  58. };
  59. try
  60. {
  61. await client.ConnectAsync(options);
  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. var applicationMessage = new MqttApplicationMessageBuilder()
  72. .WithTopic("A/B/C")
  73. .WithPayload("Hello World")
  74. .WithAtLeastOnceQoS()
  75. .Build();
  76. await client.PublishAsync(applicationMessage);
  77. }
  78. }
  79. catch (Exception exception)
  80. {
  81. Console.WriteLine(exception);
  82. }
  83. }
  84. }
  85. }