AsyncSocketListener.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System.Threading;
  6. namespace Renci.SshNet.Tests.Common
  7. {
  8. public class AsyncSocketListener : IDisposable
  9. {
  10. private readonly IPEndPoint _endPoint;
  11. private readonly ManualResetEvent _acceptCallbackDone;
  12. private readonly List<Socket> _connectedClients;
  13. private readonly object _syncLock;
  14. private Socket _listener;
  15. private Thread _receiveThread;
  16. private bool _started;
  17. private string _stackTrace;
  18. public delegate void BytesReceivedHandler(byte[] bytesReceived, Socket socket);
  19. public delegate void ConnectedHandler(Socket socket);
  20. public event BytesReceivedHandler BytesReceived;
  21. public event ConnectedHandler Connected;
  22. public event ConnectedHandler Disconnected;
  23. public AsyncSocketListener(IPEndPoint endPoint)
  24. {
  25. _endPoint = endPoint;
  26. _acceptCallbackDone = new ManualResetEvent(false);
  27. _connectedClients = new List<Socket>();
  28. _syncLock = new object();
  29. ShutdownRemoteCommunicationSocket = true;
  30. }
  31. /// <summary>
  32. /// Gets a value indicating whether the <see cref="Socket.Shutdown(SocketShutdown)"/> is invoked on the <see cref="Socket"/>
  33. /// that is used to handle the communication with the remote host, when the remote host has closed the connection.
  34. /// </summary>
  35. /// <value>
  36. /// <see langword="true"/> to invoke <see cref="Socket.Shutdown(SocketShutdown)"/> on the <see cref="Socket"/> that is used
  37. /// to handle the communication with the remote host, when the remote host has closed the connection; otherwise,
  38. /// <see langword="false"/>. The default is <see langword="true"/>.
  39. /// </value>
  40. public bool ShutdownRemoteCommunicationSocket { get; set; }
  41. public void Start()
  42. {
  43. _listener = new Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  44. _listener.Bind(_endPoint);
  45. _listener.Listen(1);
  46. _started = true;
  47. _receiveThread = new Thread(StartListener);
  48. _receiveThread.Start(_listener);
  49. _stackTrace = Environment.StackTrace;
  50. }
  51. public void Stop()
  52. {
  53. _started = false;
  54. lock (_syncLock)
  55. {
  56. foreach (var connectedClient in _connectedClients)
  57. {
  58. try
  59. {
  60. connectedClient.Shutdown(SocketShutdown.Send);
  61. }
  62. catch (Exception ex)
  63. {
  64. Console.Error.WriteLine("[{0}] Failure shutting down socket: {1}",
  65. typeof(AsyncSocketListener).FullName,
  66. ex);
  67. }
  68. DrainSocket(connectedClient);
  69. connectedClient.Dispose();
  70. }
  71. _connectedClients.Clear();
  72. }
  73. _listener?.Dispose();
  74. if (_receiveThread != null)
  75. {
  76. _receiveThread.Join();
  77. _receiveThread = null;
  78. }
  79. }
  80. public void Dispose()
  81. {
  82. Stop();
  83. GC.SuppressFinalize(this);
  84. }
  85. private void StartListener(object state)
  86. {
  87. try
  88. {
  89. var listener = (Socket)state;
  90. while (_started)
  91. {
  92. _ = _acceptCallbackDone.Reset();
  93. _ = listener.BeginAccept(AcceptCallback, listener);
  94. _ = _acceptCallbackDone.WaitOne();
  95. }
  96. }
  97. catch (Exception ex)
  98. {
  99. // On .NET framework when Thread throws an exception then unit tests
  100. // were executed without any problem.
  101. // On new .NET exceptions from Thread breaks unit tests session.
  102. Console.Error.WriteLine("[{0}] Failure in StartListener: {1}",
  103. typeof(AsyncSocketListener).FullName,
  104. ex);
  105. }
  106. }
  107. private void AcceptCallback(IAsyncResult ar)
  108. {
  109. // Signal the main thread to continue
  110. _ = _acceptCallbackDone.Set();
  111. // Get the socket that listens for inbound connections
  112. var listener = (Socket)ar.AsyncState;
  113. // Get the socket that handles the client request
  114. Socket handler;
  115. try
  116. {
  117. handler = listener.EndAccept(ar);
  118. }
  119. catch (SocketException ex)
  120. {
  121. // The listener is stopped through a Dispose() call, which in turn causes
  122. // Socket.EndAccept(...) to throw a SocketException or
  123. // ObjectDisposedException
  124. //
  125. // Since we consider such an exception normal when the listener is being
  126. // stopped, we only write a message to stderr if the listener is considered
  127. // to be up and running
  128. if (_started)
  129. {
  130. Console.Error.WriteLine("[{0}] Failure accepting new connection: {1}",
  131. typeof(AsyncSocketListener).FullName,
  132. ex);
  133. }
  134. return;
  135. }
  136. catch (ObjectDisposedException ex)
  137. {
  138. // The listener is stopped through a Dispose() call, which in turn causes
  139. // Socket.EndAccept(IAsyncResult) to throw a SocketException or
  140. // ObjectDisposedException
  141. //
  142. // Since we consider such an exception normal when the listener is being
  143. // stopped, we only write a message to stderr if the listener is considered
  144. // to be up and running
  145. if (_started)
  146. {
  147. Console.Error.WriteLine("[{0}] Failure accepting new connection: {1}",
  148. typeof(AsyncSocketListener).FullName,
  149. ex);
  150. }
  151. return;
  152. }
  153. // Signal new connection
  154. SignalConnected(handler);
  155. lock (_syncLock)
  156. {
  157. // Register client socket
  158. _connectedClients.Add(handler);
  159. }
  160. var state = new SocketStateObject(handler);
  161. try
  162. {
  163. _ =handler.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, ReadCallback, state);
  164. }
  165. catch (SocketException ex)
  166. {
  167. // The listener is stopped through a Dispose() call, which in turn causes
  168. // Socket.BeginReceive(...) to throw a SocketException or
  169. // ObjectDisposedException
  170. //
  171. // Since we consider such an exception normal when the listener is being
  172. // stopped, we only write a message to stderr if the listener is considered
  173. // to be up and running
  174. if (_started)
  175. {
  176. Console.Error.WriteLine("[{0}] Failure receiving new data: {1}",
  177. typeof(AsyncSocketListener).FullName,
  178. ex);
  179. }
  180. }
  181. catch (ObjectDisposedException ex)
  182. {
  183. // The listener is stopped through a Dispose() call, which in turn causes
  184. // Socket.BeginReceive(...) to throw a SocketException or
  185. // ObjectDisposedException
  186. //
  187. // Since we consider such an exception normal when the listener is being
  188. // stopped, we only write a message to stderr if the listener is considered
  189. // to be up and running
  190. if (_started)
  191. {
  192. Console.Error.WriteLine("[{0}] Failure receiving new data: {1}",
  193. typeof(AsyncSocketListener).FullName,
  194. ex);
  195. }
  196. }
  197. }
  198. private void ReadCallback(IAsyncResult ar)
  199. {
  200. // Retrieve the state object and the handler socket
  201. // from the asynchronous state object
  202. var state = (SocketStateObject)ar.AsyncState;
  203. var handler = state.Socket;
  204. int bytesRead;
  205. try
  206. {
  207. // Read data from the client socket.
  208. bytesRead = handler.EndReceive(ar, out var errorCode);
  209. if (errorCode != SocketError.Success)
  210. {
  211. bytesRead = 0;
  212. }
  213. }
  214. catch (SocketException ex)
  215. {
  216. // The listener is stopped through a Dispose() call, which in turn causes
  217. // Socket.EndReceive(...) to throw a SocketException or
  218. // ObjectDisposedException
  219. //
  220. // Since we consider such an exception normal when the listener is being
  221. // stopped, we only write a message to stderr if the listener is considered
  222. // to be up and running
  223. if (_started)
  224. {
  225. Console.Error.WriteLine("[{0}] Failure receiving new data: {1}",
  226. typeof(AsyncSocketListener).FullName,
  227. ex);
  228. }
  229. return;
  230. }
  231. catch (ObjectDisposedException ex)
  232. {
  233. // The listener is stopped through a Dispose() call, which in turn causes
  234. // Socket.EndReceive(...) to throw a SocketException or
  235. // ObjectDisposedException
  236. //
  237. // Since we consider such an exception normal when the listener is being
  238. // stopped, we only write a message to stderr if the listener is considered
  239. // to be up and running
  240. if (_started)
  241. {
  242. Console.Error.WriteLine("[{0}] Failure receiving new data: {1}",
  243. typeof(AsyncSocketListener).FullName,
  244. ex);
  245. }
  246. return;
  247. }
  248. void ConnectionDisconnected()
  249. {
  250. SignalDisconnected(handler);
  251. if (ShutdownRemoteCommunicationSocket)
  252. {
  253. lock (_syncLock)
  254. {
  255. if (!_started)
  256. {
  257. return;
  258. }
  259. try
  260. {
  261. handler.Shutdown(SocketShutdown.Send);
  262. handler.Close();
  263. }
  264. catch (SocketException ex) when (ex.SocketErrorCode == SocketError.ConnectionReset)
  265. {
  266. // On .NET 7 we got Socker Exception with ConnectionReset from Shutdown method
  267. // when the socket is disposed
  268. }
  269. catch (SocketException ex)
  270. {
  271. throw new Exception("Exception in ReadCallback: " + ex.SocketErrorCode + " " + _stackTrace, ex);
  272. }
  273. catch (Exception ex)
  274. {
  275. throw new Exception("Exception in ReadCallback: " + _stackTrace, ex);
  276. }
  277. _ = _connectedClients.Remove(handler);
  278. }
  279. }
  280. }
  281. if (bytesRead > 0)
  282. {
  283. var bytesReceived = new byte[bytesRead];
  284. Array.Copy(state.Buffer, bytesReceived, bytesRead);
  285. SignalBytesReceived(bytesReceived, handler);
  286. try
  287. {
  288. _ = handler.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, ReadCallback, state);
  289. }
  290. catch (ObjectDisposedException)
  291. {
  292. // TODO On .NET 7, sometimes we get ObjectDisposedException when _started but only on appveyor, locally it works
  293. ConnectionDisconnected();
  294. }
  295. catch (SocketException ex)
  296. {
  297. if (!_started)
  298. {
  299. throw new Exception("BeginReceive while stopping!", ex);
  300. }
  301. throw new Exception("BeginReceive while started!: " + ex.SocketErrorCode + " " + _stackTrace, ex);
  302. }
  303. }
  304. else
  305. {
  306. ConnectionDisconnected();
  307. }
  308. }
  309. private void SignalBytesReceived(byte[] bytesReceived, Socket client)
  310. {
  311. BytesReceived?.Invoke(bytesReceived, client);
  312. }
  313. private void SignalConnected(Socket client)
  314. {
  315. Connected?.Invoke(client);
  316. }
  317. private void SignalDisconnected(Socket client)
  318. {
  319. Disconnected?.Invoke(client);
  320. }
  321. private static void DrainSocket(Socket socket)
  322. {
  323. var buffer = new byte[128];
  324. try
  325. {
  326. while (true && socket.Connected)
  327. {
  328. var bytesRead = socket.Receive(buffer);
  329. if (bytesRead == 0)
  330. {
  331. break;
  332. }
  333. }
  334. }
  335. catch (SocketException ex)
  336. {
  337. Console.Error.WriteLine("[{0}] Failure draining socket ({1}): {2}",
  338. typeof(AsyncSocketListener).FullName,
  339. ex.SocketErrorCode.ToString("G"),
  340. ex);
  341. }
  342. }
  343. private class SocketStateObject
  344. {
  345. public Socket Socket { get; private set; }
  346. public readonly byte[] Buffer = new byte[2048];
  347. public SocketStateObject(Socket handler)
  348. {
  349. Socket = handler;
  350. }
  351. }
  352. }
  353. }