AsyncSocketListener.cs 14 KB

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