TcpClient.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. // System.Net.Sockets.TcpClient.cs
  2. //
  3. // Author:
  4. // Phillip Pearson ([email protected])
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // Copyright (C) 2001, Phillip Pearson
  8. // http://www.myelin.co.nz
  9. // Copyright (c) 2006 Novell, Inc. (http://www.novell.com)
  10. //
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Net;
  33. namespace System.Net.Sockets
  34. {
  35. public class TcpClient : IDisposable {
  36. enum Properties : uint {
  37. LingerState = 1,
  38. NoDelay = 2,
  39. ReceiveBufferSize = 4,
  40. ReceiveTimeout = 8,
  41. SendBufferSize = 16,
  42. SendTimeout = 32
  43. }
  44. // private data
  45. NetworkStream stream;
  46. bool active;
  47. Socket client;
  48. bool disposed;
  49. Properties values;
  50. int recv_timeout, send_timeout;
  51. int recv_buffer_size, send_buffer_size;
  52. LingerOption linger_state;
  53. bool no_delay;
  54. private void Init (AddressFamily family)
  55. {
  56. active = false;
  57. if(client != null) {
  58. client.Close();
  59. client = null;
  60. }
  61. client = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
  62. }
  63. public TcpClient ()
  64. {
  65. Init(AddressFamily.InterNetwork);
  66. client.Bind(new IPEndPoint(IPAddress.Any, 0));
  67. }
  68. #if NET_1_1
  69. public TcpClient (AddressFamily family)
  70. {
  71. if (family != AddressFamily.InterNetwork &&
  72. family != AddressFamily.InterNetworkV6) {
  73. throw new ArgumentException ("Family must be InterNetwork or InterNetworkV6", "family");
  74. }
  75. Init (family);
  76. client.Bind (new IPEndPoint (IPAddress.Any, 0));
  77. }
  78. #endif
  79. public TcpClient (IPEndPoint local_end_point)
  80. {
  81. Init(local_end_point.AddressFamily);
  82. client.Bind(local_end_point);
  83. }
  84. public TcpClient (string hostname, int port)
  85. {
  86. Connect(hostname, port);
  87. }
  88. protected bool Active {
  89. get { return active; }
  90. set { active = value; }
  91. }
  92. #if NET_2_0
  93. public Socket Client {
  94. #else
  95. protected Socket Client {
  96. #endif
  97. get { return client; }
  98. set {
  99. client = value;
  100. stream = null;
  101. }
  102. }
  103. #if NET_2_0
  104. public int Available {
  105. get { return client.Available; }
  106. }
  107. public bool Connected {
  108. get { return client.Connected; }
  109. }
  110. public bool ExclusiveAddressUse {
  111. get {
  112. return !((bool) client.GetSocketOption (SocketOptionLevel.Socket,
  113. SocketOptionName.ReuseAddress));
  114. }
  115. set {
  116. client.SetSocketOption (SocketOptionLevel.Socket,
  117. SocketOptionName.ReuseAddress, !value);
  118. }
  119. }
  120. #endif
  121. internal void SetTcpClient (Socket s)
  122. {
  123. Client = s;
  124. }
  125. public LingerOption LingerState {
  126. get {
  127. if ((values & Properties.LingerState) != 0)
  128. return linger_state;
  129. return (LingerOption) client.GetSocketOption (SocketOptionLevel.Socket,
  130. SocketOptionName.Linger);
  131. }
  132. set {
  133. if (!client.Connected) {
  134. linger_state = value;
  135. values |= Properties.LingerState;
  136. return;
  137. }
  138. client.SetSocketOption(
  139. SocketOptionLevel.Socket,
  140. SocketOptionName.Linger, value);
  141. }
  142. }
  143. public bool NoDelay {
  144. get {
  145. if ((values & Properties.NoDelay) != 0)
  146. return no_delay;
  147. return (bool)client.GetSocketOption(
  148. SocketOptionLevel.Tcp,
  149. SocketOptionName.NoDelay);
  150. }
  151. set {
  152. if (!client.Connected) {
  153. no_delay = value;
  154. values |= Properties.NoDelay;
  155. return;
  156. }
  157. client.SetSocketOption(
  158. SocketOptionLevel.Tcp,
  159. SocketOptionName.NoDelay, value ? 1 : 0);
  160. }
  161. }
  162. public int ReceiveBufferSize {
  163. get {
  164. if ((values & Properties.ReceiveBufferSize) != 0)
  165. return recv_buffer_size;
  166. return (int)client.GetSocketOption(
  167. SocketOptionLevel.Socket,
  168. SocketOptionName.ReceiveBuffer);
  169. }
  170. set {
  171. if (!client.Connected) {
  172. recv_buffer_size = value;
  173. values |= Properties.ReceiveBufferSize;
  174. return;
  175. }
  176. client.SetSocketOption(
  177. SocketOptionLevel.Socket,
  178. SocketOptionName.ReceiveBuffer, value);
  179. }
  180. }
  181. public int ReceiveTimeout {
  182. get {
  183. if ((values & Properties.ReceiveTimeout) != 0)
  184. return recv_timeout;
  185. return (int)client.GetSocketOption(
  186. SocketOptionLevel.Socket,
  187. SocketOptionName.ReceiveTimeout);
  188. }
  189. set {
  190. if (!client.Connected) {
  191. recv_timeout = value;
  192. values |= Properties.ReceiveTimeout;
  193. return;
  194. }
  195. client.SetSocketOption(
  196. SocketOptionLevel.Socket,
  197. SocketOptionName.ReceiveTimeout, value);
  198. }
  199. }
  200. public int SendBufferSize {
  201. get {
  202. if ((values & Properties.SendBufferSize) != 0)
  203. return send_buffer_size;
  204. return (int)client.GetSocketOption(
  205. SocketOptionLevel.Socket,
  206. SocketOptionName.SendBuffer);
  207. }
  208. set {
  209. if (!client.Connected) {
  210. send_buffer_size = value;
  211. values |= Properties.SendBufferSize;
  212. return;
  213. }
  214. client.SetSocketOption(
  215. SocketOptionLevel.Socket,
  216. SocketOptionName.SendBuffer, value);
  217. }
  218. }
  219. public int SendTimeout {
  220. get {
  221. if ((values & Properties.SendTimeout) != 0)
  222. return send_timeout;
  223. return (int)client.GetSocketOption(
  224. SocketOptionLevel.Socket,
  225. SocketOptionName.SendTimeout);
  226. }
  227. set {
  228. if (!client.Connected) {
  229. send_timeout = value;
  230. values |= Properties.SendTimeout;
  231. return;
  232. }
  233. client.SetSocketOption(
  234. SocketOptionLevel.Socket,
  235. SocketOptionName.SendTimeout, value);
  236. }
  237. }
  238. // methods
  239. public void Close ()
  240. {
  241. ((IDisposable) this).Dispose ();
  242. }
  243. public void Connect (IPEndPoint remote_end_point)
  244. {
  245. try {
  246. client.Connect(remote_end_point);
  247. stream = new NetworkStream(client, true);
  248. active = true;
  249. } finally {
  250. CheckDisposed ();
  251. }
  252. }
  253. public void Connect (IPAddress address, int port)
  254. {
  255. Connect(new IPEndPoint(address, port));
  256. }
  257. void SetOptions ()
  258. {
  259. Properties props = values;
  260. values = 0;
  261. if ((props & Properties.LingerState) != 0)
  262. LingerState = linger_state;
  263. if ((props & Properties.NoDelay) != 0)
  264. NoDelay = no_delay;
  265. if ((props & Properties.ReceiveBufferSize) != 0)
  266. ReceiveBufferSize = recv_buffer_size;
  267. if ((props & Properties.ReceiveTimeout) != 0)
  268. ReceiveTimeout = recv_timeout;
  269. if ((props & Properties.SendBufferSize) != 0)
  270. SendBufferSize = send_buffer_size;
  271. if ((props & Properties.SendTimeout) != 0)
  272. SendTimeout = send_timeout;
  273. }
  274. public void Connect (string hostname, int port)
  275. {
  276. CheckDisposed ();
  277. IPHostEntry host = Dns.GetHostByName(hostname);
  278. for(int i=0; i<host.AddressList.Length; i++) {
  279. try {
  280. Init(host.AddressList[i].AddressFamily);
  281. if(host.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
  282. client.Bind(new IPEndPoint(IPAddress.Any, 0));
  283. #if NET_1_1
  284. else if(host.AddressList[i].AddressFamily == AddressFamily.InterNetworkV6)
  285. client.Bind(new IPEndPoint(IPAddress.IPv6Any, 0));
  286. #endif
  287. Connect(new IPEndPoint(host.AddressList[i], port));
  288. if (values != 0)
  289. SetOptions ();
  290. break;
  291. } catch (Exception e) {
  292. if(client != null) {
  293. client.Close();
  294. client = null;
  295. }
  296. /// This is the last known address, re-throw the exception
  297. if(i == host.AddressList.Length-1)
  298. throw e;
  299. }
  300. }
  301. }
  302. void IDisposable.Dispose ()
  303. {
  304. Dispose (true);
  305. GC.SuppressFinalize (this);
  306. }
  307. protected virtual void Dispose (bool disposing)
  308. {
  309. if (disposed)
  310. return;
  311. disposed = true;
  312. if (disposing){
  313. // release managed resources
  314. NetworkStream s = stream;
  315. stream = null;
  316. if (s != null) {
  317. // This closes the socket as well, as the NetworkStream
  318. // owns the socket.
  319. s.Close();
  320. active = false;
  321. s = null;
  322. } else if (client != null){
  323. client.Close ();
  324. }
  325. client = null;
  326. }
  327. }
  328. ~TcpClient ()
  329. {
  330. Dispose (false);
  331. }
  332. public NetworkStream GetStream()
  333. {
  334. try {
  335. if (stream == null)
  336. stream = new NetworkStream (client, true);
  337. return stream;
  338. }
  339. finally { CheckDisposed (); }
  340. }
  341. private void CheckDisposed ()
  342. {
  343. if (disposed)
  344. throw new ObjectDisposedException (GetType().FullName);
  345. }
  346. }
  347. }