25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

97 lines
3.2 KiB

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