Advertisement
Guest User

Untitled

a guest
Apr 9th, 2020
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.87 KB | None | 0 0
  1. #define TCP
  2. //#undef TCP
  3.  
  4. using NetSharp.Sockets.Datagram;
  5. using NetSharp.Sockets.Stream;
  6.  
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Diagnostics;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Net.Sockets;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16.  
  17. using NetworkPacket = NetSharp.Packets.NetworkPacket;
  18. using SocketServer = NetSharp.Sockets.SocketServer;
  19.  
  20. namespace NetSharpExamples
  21. {
  22. internal class Program
  23. {
  24. private const int NetworkTimeout = 1_000_000;
  25. private const int ServerPort = 12374;
  26. private static readonly IPAddress ServerAddress = IPAddress.Parse("192.168.0.15");
  27. private static readonly EndPoint ServerEndPoint = new IPEndPoint(ServerAddress, ServerPort);
  28.  
  29. private static async Task Main()
  30. {
  31. Console.WriteLine("Hello World!");
  32.  
  33. await Task.Factory.StartNew(TestSocketServer);
  34. await Task.Factory.StartNew(TestSocketClient).Result;
  35.  
  36. Console.ReadLine();
  37. }
  38.  
  39. #region Socket Tests
  40.  
  41. private static async Task TestSocketClient()
  42. {
  43. const int clientCount = 20;
  44. const long packetsToSend = 100_000;
  45.  
  46. Task[] clientTasks = new Task[clientCount];
  47. double[] clientBandwidths = new double[clientCount];
  48. HashSet<int> activeTasks = new HashSet<int>(clientCount);
  49.  
  50. async void ClientTask(object id)
  51. {
  52. try
  53. {
  54. lock (typeof(Console))
  55. {
  56. Console.WriteLine($"[Client {id}] Starting client...");
  57. }
  58.  
  59. #if TCP
  60. using StreamSocketClient client = new StreamSocketClient(AddressFamily.InterNetwork, ProtocolType.Tcp);
  61. #else
  62. using DatagramSocketClient client = new DatagramSocketClient(AddressFamily.InterNetwork, ProtocolType.Udp);
  63. #endif
  64.  
  65. try
  66. {
  67. client.Bind(new IPEndPoint(IPAddress.Any, 0));
  68. }
  69. catch (SocketException)
  70. {
  71. lock (typeof(Console))
  72. {
  73. Console.WriteLine($"[Client {id}] Could not bind client socket within timeout!");
  74. return;
  75. }
  76. }
  77. #if TCP
  78. client.Connect(in ServerEndPoint);
  79. #endif
  80.  
  81. byte[] requestBuffer = new byte[NetworkPacket.TotalSize];
  82. Memory<byte> requestBufferMemory = new Memory<byte>(requestBuffer);
  83.  
  84. byte[] responseBuffer = new byte[NetworkPacket.TotalSize];
  85. Memory<byte> responseBufferMemory = new Memory<byte>(responseBuffer);
  86.  
  87. Stopwatch rttStopwatch = new Stopwatch();
  88. Stopwatch bandwidthStopwatch = new Stopwatch();
  89.  
  90. long minRttTicks = int.MaxValue, maxRttTicks = int.MinValue;
  91. long minRttMs = int.MaxValue, maxRttMs = int.MinValue;
  92.  
  93. for (int i = 0; i < packetsToSend; i++)
  94. {
  95. Encoding.UTF8.GetBytes($"Hello World! (Packet {i})").CopyTo(requestBufferMemory);
  96.  
  97. rttStopwatch.Start();
  98. bandwidthStopwatch.Start();
  99. #if TCP
  100. int sendResult = client.SendBytes(requestBufferMemory);
  101. #else
  102. int sendResult = client.SendBytesTo(requestBufferMemory, ServerEndPoint);
  103. #endif
  104.  
  105. bandwidthStopwatch.Stop();
  106. rttStopwatch.Stop();
  107.  
  108. #if DEBUG
  109. lock (typeof(Console))
  110. {
  111. Console.WriteLine($"[Client {id}, Packet {i}] Sent {sendResult} bytes to {ServerEndPoint}");
  112. Console.WriteLine($"[Client {id}, Packet {i}] >>>> {Encoding.UTF8.GetString(requestBufferMemory.Span)}");
  113. }
  114. #endif
  115.  
  116. rttStopwatch.Start();
  117. bandwidthStopwatch.Start();
  118. EndPoint serverEndPoint = ServerEndPoint;
  119.  
  120. #if TCP
  121. int receiveResult = client.ReceiveBytes(responseBufferMemory);
  122. #else
  123. int receiveResult = client.ReceiveBytesFrom(responseBufferMemory, ref serverEndPoint);
  124. #endif
  125.  
  126. bandwidthStopwatch.Stop();
  127. rttStopwatch.Stop();
  128.  
  129. #if DEBUG
  130. lock (typeof(Console))
  131. {
  132. Console.WriteLine($"[Client {id}, Packet {i}] Received {receiveResult} bytes from {serverEndPoint}");
  133. Console.WriteLine($"[Client {id}, Packet {i}] <<<< {Encoding.UTF8.GetString(responseBufferMemory.Span)}");
  134. }
  135. #endif
  136.  
  137. lock (typeof(Console))
  138. {
  139. if (!activeTasks.Contains((int)id))
  140. {
  141. activeTasks.Add((int)id);
  142. }
  143.  
  144. #if DEBUG
  145. Console.WriteLine($"[Client {id}] Client Round Trip Time: {rttStopwatch.ElapsedTicks} ticks ({rttStopwatch.ElapsedMilliseconds} ms)");
  146. #endif
  147. minRttTicks = rttStopwatch.ElapsedTicks < minRttTicks
  148. ? rttStopwatch.ElapsedTicks
  149. : minRttTicks;
  150.  
  151. minRttMs = rttStopwatch.ElapsedMilliseconds < minRttMs
  152. ? rttStopwatch.ElapsedMilliseconds
  153. : minRttMs;
  154.  
  155. maxRttTicks = rttStopwatch.ElapsedTicks > maxRttTicks
  156. ? rttStopwatch.ElapsedTicks
  157. : maxRttTicks;
  158.  
  159. maxRttMs = rttStopwatch.ElapsedMilliseconds > maxRttMs
  160. ? rttStopwatch.ElapsedMilliseconds
  161. : maxRttMs;
  162.  
  163. rttStopwatch.Reset();
  164. }
  165. }
  166.  
  167. #if TCP
  168. client.Disconnect();
  169. client.Shutdown(SocketShutdown.Both);
  170. #endif
  171.  
  172. long millis = bandwidthStopwatch.ElapsedMilliseconds;
  173. double megabytes = packetsToSend * NetworkPacket.DataSize / 1_000_000.0;
  174. double bandwidth = megabytes / (millis / 1000.0);
  175.  
  176. clientBandwidths[(int)id] = bandwidth;
  177.  
  178. lock (typeof(Console))
  179. {
  180. Console.WriteLine($"[Client {id}] Sent {packetsToSend} packets to {ServerEndPoint} in {millis} milliseconds");
  181. Console.WriteLine($"[Client {id}] Approximate bandwidth: {bandwidth:F3} MBps");
  182.  
  183. Console.WriteLine($"[Client {id}] Min RTT: {minRttTicks} ticks, {minRttMs} ms");
  184. Console.WriteLine($"[Client {id}] Max RTT: {maxRttTicks} ticks, {maxRttMs} ms");
  185.  
  186. Console.WriteLine($"[Client {id}] Stopping client...");
  187. }
  188. }
  189. catch (Exception ex)
  190. {
  191. Console.WriteLine(ex);
  192. throw;
  193. }
  194. }
  195.  
  196. for (int clientId = 0; clientId < clientCount; clientId++)
  197. {
  198. clientTasks[clientId] = Task.Factory.StartNew(ClientTask, clientId, TaskCreationOptions.LongRunning);
  199. }
  200.  
  201. await Task.WhenAll(clientTasks);
  202.  
  203. int totalActiveThreads = 0;
  204. for (int i = 0; i < clientCount; i++)
  205. {
  206. Task clientThread = clientTasks[i];
  207.  
  208. bool threadWasActive = activeTasks.Contains(i);
  209. if (threadWasActive)
  210. {
  211. totalActiveThreads++;
  212. }
  213.  
  214. Console.WriteLine($"[Client task {i}] Approx bandwidth: {clientBandwidths[i]}, was active? {threadWasActive}");
  215. }
  216.  
  217. Console.WriteLine($"Total server bandwidth: {clientBandwidths.Sum():F3} MBps, Total Active Threads: {totalActiveThreads}, Total Inactive Threads: {clientCount - totalActiveThreads}");
  218. }
  219.  
  220. private static async Task TestSocketServer()
  221. {
  222. #if TCP
  223. using SocketServer server = new StreamSocketServer(AddressFamily.InterNetwork, ProtocolType.Tcp);
  224. #else
  225. using SocketServer server = new DatagramSocketServer(AddressFamily.InterNetwork, ProtocolType.Udp);
  226. #endif
  227.  
  228. server.Bind(in ServerEndPoint);
  229.  
  230. await server.RunAsync();
  231. }
  232.  
  233. #endregion Socket Tests
  234. }
  235. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement