4 // Phillip Pearson (pp@myelin.co.nz)
5 // Gonzalo Paniagua Javier (gonzalo@novell.com)
6 // Sridhar Kulkarni (sridharkulkarni@gmail.com)
7 // Marek Safar (marek.safar@gmail.com)
9 // Copyright (C) 2001, Phillip Pearson http://www.myelin.co.nz
10 // Copyright (c) 2006 Novell, Inc. (http://www.novell.com)
11 // Copyright 2011 Xamarin Inc.
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38 using System.Threading.Tasks;
41 namespace System.Net.Sockets
43 public class TcpClient : IDisposable {
44 enum Properties : uint {
47 ReceiveBufferSize = 4,
59 int recv_timeout, send_timeout;
60 int recv_buffer_size, send_buffer_size;
61 LingerOption linger_state;
64 private void Init (AddressFamily family)
73 client = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
78 Init(AddressFamily.InterNetwork);
79 client.Bind(new IPEndPoint(IPAddress.Any, 0));
82 internal TcpClient (Socket s)
87 public TcpClient (AddressFamily family)
89 if (family != AddressFamily.InterNetwork &&
90 family != AddressFamily.InterNetworkV6) {
91 throw new ArgumentException ("Family must be InterNetwork or InterNetworkV6", "family");
95 IPAddress any = IPAddress.Any;
96 if (family == AddressFamily.InterNetworkV6)
97 any = IPAddress.IPv6Any;
98 client.Bind (new IPEndPoint (any, 0));
101 public TcpClient (IPEndPoint localEP)
103 Init (localEP.AddressFamily);
104 client.Bind (localEP);
107 public TcpClient (string hostname, int port)
109 Connect(hostname, port);
112 protected bool Active {
113 get { return active; }
114 set { active = value; }
117 public Socket Client {
118 get { return client; }
125 public int Available {
126 get { return client.Available; }
129 public bool Connected {
130 get { return client.Connected; }
133 public bool ExclusiveAddressUse {
135 return(client.ExclusiveAddressUse);
138 client.ExclusiveAddressUse = value;
142 public LingerOption LingerState {
144 if ((values & Properties.LingerState) != 0)
147 return (LingerOption) client.GetSocketOption (SocketOptionLevel.Socket,
148 SocketOptionName.Linger);
151 if (!client.Connected) {
152 linger_state = value;
153 values |= Properties.LingerState;
156 client.SetSocketOption(
157 SocketOptionLevel.Socket,
158 SocketOptionName.Linger, value);
162 public bool NoDelay {
164 if ((values & Properties.NoDelay) != 0)
167 return (bool)client.GetSocketOption(
168 SocketOptionLevel.Tcp,
169 SocketOptionName.NoDelay);
172 if (!client.Connected) {
174 values |= Properties.NoDelay;
177 client.SetSocketOption(
178 SocketOptionLevel.Tcp,
179 SocketOptionName.NoDelay, value ? 1 : 0);
183 public int ReceiveBufferSize {
185 if ((values & Properties.ReceiveBufferSize) != 0)
186 return recv_buffer_size;
188 return (int)client.GetSocketOption(
189 SocketOptionLevel.Socket,
190 SocketOptionName.ReceiveBuffer);
193 if (!client.Connected) {
194 recv_buffer_size = value;
195 values |= Properties.ReceiveBufferSize;
198 client.SetSocketOption(
199 SocketOptionLevel.Socket,
200 SocketOptionName.ReceiveBuffer, value);
204 public int ReceiveTimeout {
206 if ((values & Properties.ReceiveTimeout) != 0)
209 return (int)client.GetSocketOption(
210 SocketOptionLevel.Socket,
211 SocketOptionName.ReceiveTimeout);
214 if (!client.Connected) {
215 recv_timeout = value;
216 values |= Properties.ReceiveTimeout;
219 client.SetSocketOption(
220 SocketOptionLevel.Socket,
221 SocketOptionName.ReceiveTimeout, value);
225 public int SendBufferSize {
227 if ((values & Properties.SendBufferSize) != 0)
228 return send_buffer_size;
230 return (int)client.GetSocketOption(
231 SocketOptionLevel.Socket,
232 SocketOptionName.SendBuffer);
235 if (!client.Connected) {
236 send_buffer_size = value;
237 values |= Properties.SendBufferSize;
240 client.SetSocketOption(
241 SocketOptionLevel.Socket,
242 SocketOptionName.SendBuffer, value);
246 public int SendTimeout {
248 if ((values & Properties.SendTimeout) != 0)
251 return (int)client.GetSocketOption(
252 SocketOptionLevel.Socket,
253 SocketOptionName.SendTimeout);
256 if (!client.Connected) {
257 send_timeout = value;
258 values |= Properties.SendTimeout;
261 client.SetSocketOption(
262 SocketOptionLevel.Socket,
263 SocketOptionName.SendTimeout, value);
272 ((IDisposable) this).Dispose ();
275 public void Connect (IPEndPoint remoteEP)
278 client.Connect (remoteEP);
285 public void Connect (IPAddress address, int port)
287 Connect(new IPEndPoint(address, port));
292 Properties props = values;
295 if ((props & Properties.LingerState) != 0)
296 LingerState = linger_state;
297 if ((props & Properties.NoDelay) != 0)
299 if ((props & Properties.ReceiveBufferSize) != 0)
300 ReceiveBufferSize = recv_buffer_size;
301 if ((props & Properties.ReceiveTimeout) != 0)
302 ReceiveTimeout = recv_timeout;
303 if ((props & Properties.SendBufferSize) != 0)
304 SendBufferSize = send_buffer_size;
305 if ((props & Properties.SendTimeout) != 0)
306 SendTimeout = send_timeout;
309 public void Connect (string hostname, int port)
311 IPAddress [] addresses = Dns.GetHostAddresses (hostname);
312 Connect (addresses, port);
315 public void Connect (IPAddress[] ipAddresses, int port)
319 if (ipAddresses == null) {
320 throw new ArgumentNullException ("ipAddresses");
323 for(int i = 0; i < ipAddresses.Length; i++) {
325 IPAddress address = ipAddresses[i];
327 if (address.Equals (IPAddress.Any) ||
328 address.Equals (IPAddress.IPv6Any)) {
329 throw new SocketException ((int)SocketError.AddressNotAvailable);
332 Init (address.AddressFamily);
334 if (address.AddressFamily == AddressFamily.InterNetwork) {
335 client.Bind (new IPEndPoint (IPAddress.Any, 0));
336 } else if (address.AddressFamily == AddressFamily.InterNetworkV6) {
337 client.Bind (new IPEndPoint (IPAddress.IPv6Any, 0));
339 throw new NotSupportedException ("This method is only valid for sockets in the InterNetwork and InterNetworkV6 families");
342 Connect (new IPEndPoint (address, port));
349 } catch (Exception e) {
350 /* Reinitialise the socket so
351 * other properties still work
352 * (see no-arg constructor)
354 Init (AddressFamily.InterNetwork);
356 /* This is the last known
357 * address, so re-throw the
360 if (i == ipAddresses.Length - 1) {
367 public void EndConnect (IAsyncResult asyncResult)
369 client.EndConnect (asyncResult);
372 public IAsyncResult BeginConnect (IPAddress address, int port, AsyncCallback requestCallback, object state)
374 return client.BeginConnect (address, port, requestCallback, state);
377 public IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
379 return client.BeginConnect (addresses, port, requestCallback, state);
382 public IAsyncResult BeginConnect (string host, int port, AsyncCallback requestCallback, object state)
384 return client.BeginConnect (host, port, requestCallback, state);
387 void IDisposable.Dispose ()
390 GC.SuppressFinalize (this);
393 protected virtual void Dispose (bool disposing)
400 // release managed resources
401 NetworkStream s = stream;
404 // This closes the socket as well, as the NetworkStream
409 } else if (client != null){
421 public NetworkStream GetStream()
425 stream = new NetworkStream (client, true);
428 finally { CheckDisposed (); }
432 public Task ConnectAsync (IPAddress address, int port)
434 return Task.Factory.FromAsync (BeginConnect, EndConnect, address, port, null);
437 public Task ConnectAsync (IPAddress[] addresses, int port)
439 return Task.Factory.FromAsync (BeginConnect, EndConnect, addresses, port, null);
442 public Task ConnectAsync (string host, int port)
444 return Task.Factory.FromAsync (BeginConnect, EndConnect, host, port, null);
447 private void CheckDisposed ()
450 throw new ObjectDisposedException (GetType().FullName);