TcpConnectionPool.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. //
  2. // System.Runtime.Remoting.Channels.Tcp.TcpConnectionPool.cs
  3. //
  4. // Author: Lluis Sanchez Gual ([email protected])
  5. //
  6. // 2002 (C) Lluis Sanchez Gual
  7. //
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections;
  30. using System.Threading;
  31. using System.IO;
  32. using System.Net.Sockets;
  33. namespace System.Runtime.Remoting.Channels.Tcp
  34. {
  35. // This is a pool of Tcp connections. Connections requested
  36. // by the TCP channel are pooled after their use, and can
  37. // be reused later. Connections are automaticaly closed
  38. // if not used after some time, specified in KeepAliveSeconds.
  39. // The number of allowed open connections can also be specified
  40. // in MaxOpenConnections. The limit is per host.
  41. // If a thread requests a connection and the limit has been
  42. // reached, the thread is suspended until one is released.
  43. internal class TcpConnectionPool
  44. {
  45. // Table of pools. There is a HostConnectionPool
  46. // instance for each host
  47. static Hashtable _pools = new Hashtable();
  48. static int _maxOpenConnections = 50;
  49. static int _keepAliveSeconds = 15;
  50. static Thread _poolThread;
  51. static TcpConnectionPool()
  52. {
  53. // This thread will close unused connections
  54. _poolThread = new Thread (new ThreadStart (ConnectionCollector));
  55. _poolThread.Start();
  56. _poolThread.IsBackground = true;
  57. }
  58. public static void Shutdown ()
  59. {
  60. if (_poolThread != null)
  61. _poolThread.Abort();
  62. }
  63. public static int MaxOpenConnections
  64. {
  65. get { return _maxOpenConnections; }
  66. set
  67. {
  68. if (value < 1) throw new RemotingException ("MaxOpenConnections must be greater than zero");
  69. _maxOpenConnections = value;
  70. }
  71. }
  72. public static int KeepAliveSeconds
  73. {
  74. get { return _keepAliveSeconds; }
  75. set { _keepAliveSeconds = value; }
  76. }
  77. public static TcpConnection GetConnection (string host, int port)
  78. {
  79. HostConnectionPool hostPool;
  80. lock (_pools)
  81. {
  82. string key = host + ":" + port;
  83. hostPool = (HostConnectionPool) _pools[key];
  84. if (hostPool == null)
  85. {
  86. hostPool = new HostConnectionPool(host, port);
  87. _pools[key] = hostPool;
  88. }
  89. }
  90. return hostPool.GetConnection();
  91. }
  92. private static void ConnectionCollector ()
  93. {
  94. while (true)
  95. {
  96. Thread.Sleep(3000);
  97. lock (_pools)
  98. {
  99. ICollection values = _pools.Values;
  100. foreach (HostConnectionPool pool in values)
  101. pool.PurgeConnections();
  102. }
  103. }
  104. }
  105. }
  106. internal class ReusableTcpClient : TcpClient
  107. {
  108. public ReusableTcpClient (string host, int port): base (host, port)
  109. {
  110. }
  111. public bool IsAlive
  112. {
  113. get
  114. {
  115. // This Poll will return true if there is data pending to
  116. // be read. It prob. means that a client object using this
  117. // connection got an exception and did not finish to read
  118. // the data. It can also mean that the connection has been
  119. // closed in the server. In both cases, the connection cannot
  120. // be reused.
  121. return !Client.Poll (0, SelectMode.SelectRead);
  122. }
  123. }
  124. }
  125. internal class TcpConnection
  126. {
  127. DateTime _controlTime;
  128. Stream _stream;
  129. ReusableTcpClient _client;
  130. HostConnectionPool _pool;
  131. byte[] _buffer;
  132. public TcpConnection (HostConnectionPool pool, ReusableTcpClient client)
  133. {
  134. _pool = pool;
  135. _client = client;
  136. _stream = client.GetStream();
  137. _controlTime = DateTime.Now;
  138. _buffer = new byte[TcpMessageIO.DefaultStreamBufferSize];
  139. }
  140. public Stream Stream
  141. {
  142. get { return _stream; }
  143. }
  144. public DateTime ControlTime
  145. {
  146. get { return _controlTime; }
  147. set { _controlTime = value; }
  148. }
  149. public bool IsAlive
  150. {
  151. get { return _client.IsAlive; }
  152. }
  153. // This is a "thread safe" buffer that can be used by
  154. // TcpClientTransportSink to read or send data to the stream.
  155. // The buffer is "thread safe" since only one thread can
  156. // use a connection at a given time.
  157. public byte[] Buffer
  158. {
  159. get { return _buffer; }
  160. }
  161. // Returns the connection to the pool
  162. public void Release()
  163. {
  164. _pool.ReleaseConnection (this);
  165. }
  166. public void Close()
  167. {
  168. _client.Close();
  169. }
  170. }
  171. internal class HostConnectionPool
  172. {
  173. ArrayList _pool = new ArrayList();
  174. int _activeConnections = 0;
  175. string _host;
  176. int _port;
  177. public HostConnectionPool (string host, int port)
  178. {
  179. _host = host;
  180. _port = port;
  181. }
  182. public TcpConnection GetConnection ()
  183. {
  184. lock (_pool)
  185. {
  186. TcpConnection connection = null;
  187. do
  188. {
  189. if (_pool.Count > 0)
  190. {
  191. // There are available connections
  192. connection = (TcpConnection)_pool[_pool.Count - 1];
  193. _pool.RemoveAt(_pool.Count - 1);
  194. if (!connection.IsAlive) {
  195. CancelConnection (connection);
  196. connection = null;
  197. continue;
  198. }
  199. }
  200. if (connection == null && _activeConnections < TcpConnectionPool.MaxOpenConnections)
  201. {
  202. // No connections available, but the max connections
  203. // has not been reached yet, so a new one can be created
  204. connection = CreateConnection();
  205. }
  206. // No available connections in the pool
  207. // Wait for somewone to release one.
  208. if (connection == null)
  209. {
  210. Monitor.Wait(_pool);
  211. }
  212. }
  213. while (connection == null);
  214. return connection;
  215. }
  216. }
  217. private TcpConnection CreateConnection()
  218. {
  219. try
  220. {
  221. ReusableTcpClient client = new ReusableTcpClient(_host, _port);
  222. TcpConnection entry = new TcpConnection(this, client);
  223. _activeConnections++;
  224. return entry;
  225. }
  226. catch (Exception ex)
  227. {
  228. throw new RemotingException (ex.Message);
  229. }
  230. }
  231. public void ReleaseConnection (TcpConnection entry)
  232. {
  233. lock (_pool)
  234. {
  235. entry.ControlTime = DateTime.Now; // Initialize timeout
  236. _pool.Add (entry);
  237. Monitor.Pulse (_pool);
  238. }
  239. }
  240. private void CancelConnection(TcpConnection entry)
  241. {
  242. try
  243. {
  244. entry.Stream.Close();
  245. _activeConnections--;
  246. }
  247. catch
  248. {
  249. }
  250. }
  251. public void PurgeConnections()
  252. {
  253. lock (_pool)
  254. {
  255. for (int n=0; n < _pool.Count; n++)
  256. {
  257. TcpConnection entry = (TcpConnection)_pool[n];
  258. if ( (DateTime.Now - entry.ControlTime).TotalSeconds > TcpConnectionPool.KeepAliveSeconds)
  259. {
  260. CancelConnection (entry);
  261. _pool.RemoveAt(n);
  262. n--;
  263. }
  264. }
  265. }
  266. }
  267. }
  268. }