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.
 
 
 
 

194 rivejä
6.2 KiB

  1. using MQTTnet.Core;
  2. using MQTTnet.Core.Client;
  3. using MQTTnet.Core.Packets;
  4. using MQTTnet.Core.Protocol;
  5. using MQTTnet.Core.Server;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace MQTTnet.TestApp.NetFramework
  13. {
  14. public static class PerformanceTest
  15. {
  16. public static async Task RunAsync()
  17. {
  18. var server = Task.Run(() => RunServerAsync());
  19. var client = Task.Run(() => RunClientAsync(500, TimeSpan.FromMilliseconds(10)));
  20. await Task.WhenAll(server, client).ConfigureAwait(false);
  21. }
  22. private static async Task RunClientAsync( int msgChunkSize, TimeSpan interval )
  23. {
  24. try
  25. {
  26. var options = new MqttClientOptions
  27. {
  28. Server = "localhost",
  29. ClientId = "XYZ",
  30. CleanSession = true,
  31. DefaultCommunicationTimeout = TimeSpan.FromMinutes(10)
  32. };
  33. var client = new MqttClientFactory().CreateMqttClient(options);
  34. client.ApplicationMessageReceived += (s, e) =>
  35. {
  36. };
  37. client.Connected += async (s, e) =>
  38. {
  39. Console.WriteLine("### CONNECTED WITH SERVER ###");
  40. await client.SubscribeAsync(new List<TopicFilter>
  41. {
  42. new TopicFilter("#", MqttQualityOfServiceLevel.AtMostOnce)
  43. });
  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();
  53. }
  54. catch
  55. {
  56. Console.WriteLine("### RECONNECTING FAILED ###");
  57. }
  58. };
  59. try
  60. {
  61. await client.ConnectAsync();
  62. }
  63. catch (Exception exception)
  64. {
  65. Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
  66. }
  67. Console.WriteLine("### WAITING FOR APPLICATION MESSAGES ###");
  68. var last = DateTime.Now;
  69. var msgCount = 0;
  70. while (true)
  71. {
  72. var msgs = Enumerable.Range( 0, msgChunkSize )
  73. .Select( i => CreateMessage() )
  74. .ToList();
  75. if (false)
  76. {
  77. //send concurrent (test for raceconditions)
  78. var sendTasks = msgs
  79. .Select( msg => PublishSingleMessage( client, msg, ref msgCount ) )
  80. .ToList();
  81. await Task.WhenAll( sendTasks );
  82. }
  83. else
  84. {
  85. await client.PublishAsync( msgs );
  86. msgCount += msgs.Count;
  87. //send multiple
  88. }
  89. var now = DateTime.Now;
  90. if (last < now - TimeSpan.FromSeconds(1))
  91. {
  92. Console.WriteLine( $"sending {msgCount} inteded {msgChunkSize / interval.TotalSeconds}" );
  93. msgCount = 0;
  94. last = now;
  95. }
  96. await Task.Delay(interval).ConfigureAwait(false);
  97. }
  98. }
  99. catch (Exception exception)
  100. {
  101. Console.WriteLine(exception);
  102. }
  103. }
  104. private static MqttApplicationMessage CreateMessage()
  105. {
  106. return new MqttApplicationMessage(
  107. "A/B/C",
  108. Encoding.UTF8.GetBytes( "Hello World" ),
  109. MqttQualityOfServiceLevel.AtMostOnce,
  110. false
  111. );
  112. }
  113. private static Task PublishSingleMessage( IMqttClient client, MqttApplicationMessage applicationMessage, ref int count )
  114. {
  115. Interlocked.Increment( ref count );
  116. return Task.Run( () =>
  117. {
  118. return client.PublishAsync( applicationMessage );
  119. } );
  120. }
  121. private static void RunServerAsync()
  122. {
  123. try
  124. {
  125. var options = new MqttServerOptions
  126. {
  127. ConnectionValidator = p =>
  128. {
  129. if (p.ClientId == "SpecialClient")
  130. {
  131. if (p.Username != "USER" || p.Password != "PASS")
  132. {
  133. return MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
  134. }
  135. }
  136. return MqttConnectReturnCode.ConnectionAccepted;
  137. },
  138. DefaultCommunicationTimeout = TimeSpan.FromMinutes(10)
  139. };
  140. var mqttServer = new MqttServerFactory().CreateMqttServer(options);
  141. var last = DateTime.Now;
  142. var msgs = 0;
  143. mqttServer.ApplicationMessageReceived += (sender, args) =>
  144. {
  145. msgs++;
  146. var now = DateTime.Now;
  147. if (last < now - TimeSpan.FromSeconds(1))
  148. {
  149. Console.WriteLine($"received {msgs}");
  150. msgs = 0;
  151. last = now;
  152. }
  153. };
  154. mqttServer.Start();
  155. Console.WriteLine("Press any key to exit.");
  156. Console.ReadLine();
  157. mqttServer.Stop();
  158. }
  159. catch (Exception e)
  160. {
  161. Console.WriteLine(e);
  162. }
  163. Console.ReadLine();
  164. }
  165. }
  166. }