AsyncSocketListener.cs 12 KB

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