TcpClient.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. // System.Net.Sockets.TcpClient.cs
  2. //
  3. // Author:
  4. // Phillip Pearson ([email protected])
  5. //
  6. // Copyright (C) 2001, Phillip Pearson
  7. // http://www.myelin.co.nz
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. // NB: This is untested (probably buggy) code - take care if using it
  30. using System;
  31. using System.Net;
  32. namespace System.Net.Sockets
  33. {
  34. /// <remarks>
  35. /// A slightly more abstracted way to create an
  36. /// outgoing network connections than a Socket.
  37. /// </remarks>
  38. public class TcpClient : IDisposable
  39. {
  40. // private data
  41. private NetworkStream stream;
  42. private bool active;
  43. private Socket client;
  44. private bool disposed = false;
  45. // constructor
  46. /// <summary>
  47. /// Some code that is shared between the constructors.
  48. /// </summary>
  49. private void Init (AddressFamily family)
  50. {
  51. active = false;
  52. if(client != null) {
  53. client.Close();
  54. client = null;
  55. }
  56. client = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
  57. }
  58. /// <summary>
  59. /// Constructs a new TcpClient with no connection set up
  60. /// </summary>
  61. public TcpClient ()
  62. {
  63. Init(AddressFamily.InterNetwork);
  64. client.Bind(new IPEndPoint(IPAddress.Any, 0));
  65. }
  66. #if NET_1_1
  67. public TcpClient (AddressFamily family)
  68. {
  69. if (family != AddressFamily.InterNetwork &&
  70. family != AddressFamily.InterNetworkV6) {
  71. throw new ArgumentException ("Family must be InterNetwork or InterNetworkV6", "family");
  72. }
  73. Init (family);
  74. client.Bind (new IPEndPoint (IPAddress.Any, 0));
  75. }
  76. #endif
  77. /// <summary>
  78. /// Constructs a new TcpClient with a specified local endpoint.
  79. /// Use this if you want to have your connections originating
  80. /// from a certain port, or a certain IP (on a multi homed
  81. /// system).
  82. /// </summary>
  83. /// <param name="local_end_point">The aforementioned local endpoint</param>
  84. public TcpClient (IPEndPoint local_end_point)
  85. {
  86. Init(local_end_point.AddressFamily);
  87. client.Bind(local_end_point);
  88. }
  89. /// <summary>
  90. /// Constructs a new TcpClient and connects to a specified
  91. /// host on a specified port. A quick way to set up a network
  92. /// connection.
  93. /// </summary>
  94. /// <param name="hostname">The host to connect to, e.g.
  95. /// 192.168.0.201 or www.myelin.co.nz</param>
  96. /// <param name="port">The port to connect to, e.g. 80 for HTTP</param>
  97. public TcpClient (string hostname, int port)
  98. {
  99. Connect(hostname, port);
  100. }
  101. /// <summary>
  102. /// A flag that is 'true' if the TcpClient has an active connection
  103. /// </summary>
  104. protected bool Active
  105. {
  106. get { return active; }
  107. set { active = value; }
  108. }
  109. /// <summary>
  110. /// The socket that all network comms passes through
  111. /// </summary>
  112. protected Socket Client
  113. {
  114. get { return client; }
  115. set {
  116. client = value;
  117. stream = null;
  118. }
  119. }
  120. /// <summary>
  121. /// Internal function to allow TcpListener.AcceptTcpClient
  122. /// to work (it needs to be able to set protected property
  123. /// 'Client')
  124. /// </summary>
  125. /// <param name="s"></param>
  126. internal void SetTcpClient (Socket s)
  127. {
  128. Client = s;
  129. }
  130. /// <summary>
  131. /// If set, the socket will remain open after it has been
  132. /// instructed to close, in order to send data that remains
  133. /// in the buffer.
  134. /// </summary>
  135. public LingerOption LingerState
  136. {
  137. get {
  138. return (LingerOption)client.GetSocketOption(
  139. SocketOptionLevel.Socket,
  140. SocketOptionName.Linger);
  141. }
  142. set {
  143. client.SetSocketOption(
  144. SocketOptionLevel.Socket,
  145. SocketOptionName.Linger, value);
  146. }
  147. }
  148. /// <summary>
  149. /// <p>If set, outbound data will be sent at once rather than collected
  150. /// until enough is available to fill a packet.</p>
  151. ///
  152. /// <p>This is the TCP_NODELAY sockopt from BSD sockets and WinSock.
  153. /// For more information, look up the Nagle algorithm.</p>
  154. /// </summary>
  155. public bool NoDelay
  156. {
  157. get {
  158. return (bool)client.GetSocketOption(
  159. SocketOptionLevel.Tcp,
  160. SocketOptionName.NoDelay);
  161. }
  162. set {
  163. client.SetSocketOption(
  164. SocketOptionLevel.Tcp,
  165. SocketOptionName.NoDelay, value);
  166. }
  167. }
  168. /// <summary>
  169. /// How big the receive buffer is (from the connection socket)
  170. /// </summary>
  171. public int ReceiveBufferSize
  172. {
  173. get {
  174. return (int)client.GetSocketOption(
  175. SocketOptionLevel.Socket,
  176. SocketOptionName.ReceiveBuffer);
  177. }
  178. set {
  179. client.SetSocketOption(
  180. SocketOptionLevel.Socket,
  181. SocketOptionName.ReceiveBuffer, value);
  182. }
  183. }
  184. /// <summary>
  185. /// How long before the socket will time out on a
  186. /// Receive() call
  187. /// </summary>
  188. public int ReceiveTimeout
  189. {
  190. get {
  191. return (int)client.GetSocketOption(
  192. SocketOptionLevel.Socket,
  193. SocketOptionName.ReceiveTimeout);
  194. }
  195. set {
  196. client.SetSocketOption(
  197. SocketOptionLevel.Socket,
  198. SocketOptionName.ReceiveTimeout, value);
  199. }
  200. }
  201. /// <summary>
  202. /// How big the send buffer is (from the connection socket)
  203. /// </summary>
  204. public int SendBufferSize
  205. {
  206. get {
  207. return (int)client.GetSocketOption(
  208. SocketOptionLevel.Socket,
  209. SocketOptionName.SendBuffer);
  210. }
  211. set {
  212. client.SetSocketOption(
  213. SocketOptionLevel.Socket,
  214. SocketOptionName.SendBuffer, value);
  215. }
  216. }
  217. /// <summary>
  218. /// How long before the socket will time out on a
  219. /// Send() call
  220. /// </summary>
  221. public int SendTimeout
  222. {
  223. get {
  224. return (int)client.GetSocketOption(
  225. SocketOptionLevel.Socket,
  226. SocketOptionName.SendTimeout);
  227. }
  228. set {
  229. client.SetSocketOption(
  230. SocketOptionLevel.Socket,
  231. SocketOptionName.SendTimeout, value);
  232. }
  233. }
  234. // methods
  235. /// <summary>
  236. /// Closes the socket and disposes of all managed resources.
  237. ///
  238. /// Throws SocketException if something goes wrong while
  239. /// closing the socket.
  240. /// </summary>
  241. public void Close ()
  242. {
  243. ((IDisposable) this).Dispose ();
  244. }
  245. /// <summary>
  246. /// Connects to a specified remote endpoint
  247. ///
  248. /// Throws SocketException if something goes wrong while
  249. /// connecting.
  250. /// </summary>
  251. /// <param name="remote_end_point">The aforementioned endpoint</param>
  252. public void Connect (IPEndPoint remote_end_point)
  253. {
  254. try {
  255. client.Connect(remote_end_point);
  256. stream = new NetworkStream(client, true);
  257. active = true;
  258. } finally {
  259. CheckDisposed ();
  260. }
  261. }
  262. /// <summary>
  263. /// Connects to an IP address on a port
  264. ///
  265. /// Throws SocketException if something goes wrong while
  266. /// connecting.
  267. /// </summary>
  268. /// <param name="address">The IP address (get it from Dns.GetHostByName)</param>
  269. /// <param name="port">The port to connect to, e.g. 80 for HTTP</param>
  270. public void Connect (IPAddress address, int port)
  271. {
  272. Connect(new IPEndPoint(address, port));
  273. }
  274. /// <summary>
  275. /// Resolves a fully qualified domain name to an IP address
  276. /// and connects to it on a specified port
  277. ///
  278. /// Throws SocketException if something goes wrong while
  279. /// connecting.
  280. /// </summary>
  281. /// <param name="hostname">The hostname, e.g. www.myelin.co.nz</param>
  282. /// <param name="port">The port, e.g. 80 for HTTP</param>
  283. [MonoTODO]
  284. public void Connect (string hostname, int port)
  285. {
  286. CheckDisposed ();
  287. IPHostEntry host = Dns.GetHostByName(hostname);
  288. for(int i=0; i<host.AddressList.Length; i++)
  289. {
  290. try {
  291. Init(host.AddressList[i].AddressFamily);
  292. if(host.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
  293. client.Bind(new IPEndPoint(IPAddress.Any, 0));
  294. #if NET_1_1
  295. else if(host.AddressList[i].AddressFamily == AddressFamily.InterNetworkV6)
  296. client.Bind(new IPEndPoint(IPAddress.IPv6Any, 0));
  297. #endif
  298. Connect(new IPEndPoint(host.AddressList[i], port));
  299. break;
  300. }
  301. catch(Exception e) {
  302. if(client != null) {
  303. client.Close();
  304. client = null;
  305. }
  306. /// This is the last known address, re-throw the exception
  307. if(i == host.AddressList.Length-1)
  308. throw e;
  309. }
  310. }
  311. }
  312. /// <summary>
  313. /// Gets rid of all managed resources
  314. /// </summary>
  315. void IDisposable.Dispose ()
  316. {
  317. Dispose (true);
  318. GC.SuppressFinalize (this);
  319. }
  320. /// <summary>
  321. /// Gets rid of all unmanaged resources
  322. /// </summary>
  323. /// <param name="disposing">If this is true, it gets rid of all
  324. /// managed resources as well</param>
  325. protected virtual void Dispose (bool disposing)
  326. {
  327. if (disposed)
  328. return;
  329. disposed = true;
  330. if (disposing){
  331. // release managed resources
  332. NetworkStream s = stream;
  333. stream = null;
  334. if (s != null) {
  335. // This closes the socket as well, as the NetworkStream
  336. // owns the socket.
  337. s.Close();
  338. active = false;
  339. s = null;
  340. } else if (client != null){
  341. client.Close ();
  342. }
  343. client = null;
  344. }
  345. }
  346. /// <summary>
  347. /// Destructor - just calls Dispose()
  348. /// </summary>
  349. ~TcpClient ()
  350. {
  351. Dispose (false);
  352. }
  353. /// <returns>A NetworkStream object connected to the
  354. /// connection socket</returns>
  355. public NetworkStream GetStream()
  356. {
  357. try {
  358. if (stream == null)
  359. {
  360. stream = new NetworkStream (client, true);
  361. }
  362. return stream;
  363. }
  364. finally { CheckDisposed (); }
  365. }
  366. private void CheckDisposed ()
  367. {
  368. if (disposed)
  369. throw new ObjectDisposedException (GetType().FullName);
  370. }
  371. }
  372. }