public class TcpClient : IDisposable
|
To send and receive data, use the TcpClient.GetStream method to obtain a NetworkStream that can send and receive data on the underlying connected Socket. After utilizing the write and read methods available through the NetworkStream, use the TcpClient.Close method to release all resources associated with the TcpClient.
TcpClient provides a set of convenient properties that you can use to adjust common Socket settings. If you need to set Socket options not addressed with these properties, use the TcpClient.Client property to retrieve the underlying Socket.
TcpClient tcpClient = new TcpClient(); try{ tcpClient.Connect("www.contoso.com", 11000); NetworkStream networkStream = tcpClient.GetStream(); if(networkStream.CanWrite && networkStream.CanRead){ // Does a simple write. Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there"); networkStream.Write(sendBytes, 0, sendBytes.Length); // Reads the NetworkStream into a byte buffer. byte[] bytes = new byte[tcpClient.ReceiveBufferSize]; networkStream.Read(bytes, 0, (int) tcpClient.ReceiveBufferSize); // Returns the data received from the host to the console. string returndata = Encoding.ASCII.GetString(bytes); Console.WriteLine("This is what the host returned to you: " + returndata); } else if (!networkStream.CanRead){ Console.WriteLine("You can not write data to this stream"); tcpClient.Close(); } else if (!networkStream.CanWrite){ Console.WriteLine("You can not read data from this stream"); tcpClient.Close(); } } catch (Exception e ) { Console.WriteLine(e.ToString()); }
ctor #1 | Overloaded:.ctor() Default constructor. This constructor is called by derived class constructors to initialize state in this type.Initializes a new instance of the TcpClient class. |
ctor #2 | Overloaded:.ctor(IPEndPoint localEP) Initializes a new instance of TcpClient bound to the specified local endpoint. |
ctor #3 | Overloaded:.ctor(string hostname, int port) Initializes a new instance of the TcpClient class and connects to the specified port on the specified host. |
LingerState | Read-write Gets or sets information about the sockets linger time. |
NoDelay | Read-write Gets or sets a value that enables a delay when send or receive buffers are not full. |
ReceiveBufferSize | Read-write Gets or sets the size of the receive buffer. |
ReceiveTimeout | Read-write Gets or sets the amount of time a TcpClient will wait to receive data once initiated. |
SendBufferSize | Read-write Gets or sets the size of the send buffer. |
SendTimeout | Read-write Gets or sets the amount of time a TcpClient will wait to receive confirmation after you initiate a send. |
Close | Closes the TCP connection. |
Connect | Overloaded:Connect(IPEndPoint remoteEP) Connects the client to a remote TCP host using the specified remote network endpoint. |
Connect | Overloaded:Connect(IPAddress address, int port) Connects the client to a remote TCP host using the specified IP address and port number. |
Connect | Overloaded:Connect(string hostname, int port) Connects the client to the specified port on the specified host. |
Equals (inherited from System.Object) |
See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
GetHashCode (inherited from System.Object) |
See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
GetStream | Returns the stream used to send and receive data. |
GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
ToString (inherited from System.Object) |
See base class member description: System.Object.ToString Derived from System.Object, the primary base class for all objects. |
Active | Read-write Gets or set a value that indicates whether a connection has been made. |
Client | Read-write Gets or sets the underlying Socket. |
Dispose | Releases the unmanaged resources used by the TcpClient and optionally releases the managed resources. |
Finalize | Overridden: Frees resources used by the TcpClient class. |
MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
public TcpClient(); |
//Creates a TCPClient using the default constructor. TcpClient tcpClientC = new TcpClient();
public TcpClient( |
localEP
Exception Type | Condition |
---|---|
ArgumentNullException | The localEP parameter is null. |
//Creates a TCPClient using a localend point. IPAddress ipAddress = Dns.Resolve(Dns.GetHostName()).AddressList[0]; IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 11000); try{ TcpClient tcpClientA = new TcpClient(ipLocalEndPoint); } catch (Exception e ) { Console.WriteLine(e.ToString()); }
hostname
port
Exception Type | Condition |
---|---|
ArgumentNullException | The hostname parameter is null. |
ArgumentOutOfRangeException | The port parameter is not between IPEndPoint.MinPort and IPEndPoint.MaxPort. |
SocketException | An error occurred while connecting to the remote host. |
//Creates a TCPClient using hostname and port. try{ TcpClient tcpClientB = new TcpClient("www.contoso.com", 11000); } catch (Exception e ) { Console.WriteLine(e.ToString()); }
protected bool Active {get; set;}
|
MyTcpClientDerivedClass
verifies that the connection is active before obtaining the underlying Socket.// This derived class demonstrates the use of three protected methods belonging to the TcpClient class public class MyTcpClientDerivedClass : TcpClient{ // Constructor for the derived class. public MyTcpClientDerivedClass() : base(){ } public void UsingProtectedMethods(){ // Uses the protected 'Active' property belonging to the TcpClient base class // to determine if a connection is established. if (this.Active){ // Calls the protected 'Client' property belonging to the TcpClient base class. Socket s = this.Client; // Uses the Socket returned by Client to set an option that is not available using TcpClient. s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); } // To free all resources, calls the protected virtual method Dispose belonging to the TcpClient base class. this.Dispose(true); GC.SuppressFinalize(this); } }
protected Socket Client {get; set;}
|
MyTcpClientDerivedClass
obtains the underlying socket to enable broadcasting.// This derived class demonstrates the use of three protected methods belonging to the TcpClient class public class MyTcpClientDerivedClass : TcpClient{ // Constructor for the derived class. public MyTcpClientDerivedClass() : base(){ } public void UsingProtectedMethods(){ // Uses the protected 'Active' property belonging to the TcpClient base class // to determine if a connection is established. if (this.Active){ // Calls the protected 'Client' property belonging to the TcpClient base class. Socket s = this.Client; // Uses the Socket returned by Client to set an option that is not available using TcpClient. s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); } // To free all resources, calls the protected virtual method Dispose belonging to the TcpClient base class. this.Dispose(true); GC.SuppressFinalize(this); } }
public LingerOption LingerState {get; set;}
|
// sets the amount of time to linger after closing, using the LingerOption public property. LingerOption lingerOption = new LingerOption(true, 10); tcpClient.LingerState = lingerOption; // gets the amount of linger time set, using the LingerOption public property. if (tcpClient.LingerState.LingerTime == 10) Console.WriteLine("The linger state setting was successfully set to " + tcpClient.LingerState.LingerTime.ToString());
public bool NoDelay {get; set;}
|
// Sends data immediately upon calling NetworkStream.Write. tcpClient.NoDelay = true; // Determines if the delay is enabled by using the NoDelay property. if (tcpClient.NoDelay == true) Console.WriteLine("The delay was set successfully to " + tcpClient.NoDelay.ToString());
public int ReceiveBufferSize {get; set;}
|
// sets the receive buffer size using the ReceiveBufferSize public property. tcpClient.ReceiveBufferSize = 1024; // gets the receive buffer size using the ReceiveBufferSize public property. if (tcpClient.ReceiveBufferSize == 1024) Console.WriteLine("The receive buffer was successfully set to " + tcpClient.ReceiveBufferSize.ToString());
public int ReceiveTimeout {get; set;}
|
// Sets the receive time out using the ReceiveTimeout public property. tcpClient.ReceiveTimeout = 5; // Gets the receive time out using the ReceiveTimeout public property. if (tcpClient.ReceiveTimeout == 5) Console.WriteLine("The receive time out limit was successfully set " + tcpClient.ReceiveTimeout.ToString());
public int SendBufferSize {get; set;}
|
//sets the send buffer size using the SendBufferSize public property. tcpClient.SendBufferSize = 1024; // gets the send buffer size using the SendBufferSize public property. if (tcpClient.SendBufferSize == 1024) Console.WriteLine("The send buffer was successfully set to " + tcpClient.SendBufferSize.ToString());
public int SendTimeout {get; set;}
|
// sets the send time out using the SendTimeout public property. tcpClient.SendTimeout = 5; // gets the send time out using the SendTimeout public property. if (tcpClient.SendTimeout == 5) Console.WriteLine("The send time out limit was successfully set " + tcpClient.SendTimeout.ToString());
public void Close(); |
Exception Type | Condition |
---|---|
SocketException | An error occurs while closing the socket. |
// Uses the Close public method to close the network stream and socket. tcpClient.Close();
public void Connect( |
remoteEP
Exception Type | Condition |
---|---|
ArgumentNullException | The remoteEp parameter is null. |
SocketException | An error occurred while connecting to the remote host. |
//Uses a remote end point to establish a socket connection. TcpClient tcpClient = new TcpClient(); IPAddress ipAddress = Dns.Resolve("www.contoso.com").AddressList[0]; IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 11004); try{ tcpClient.Connect(ipEndPoint); } catch (Exception e ) { Console.WriteLine(e.ToString()); }
address
port
Exception Type | Condition |
---|---|
ArgumentNullException | The address parameter is null. |
ArgumentOutOfRangeException | The port parameter is not between IPEndPoint.MinPort and IPEndPoint.MaxPort. |
SocketException | An error occurred while connecting to the remote host. |
//Uses the IP address and port number to establish a socket connection. TcpClient tcpClient = new TcpClient(); IPAddress ipAddress = Dns.Resolve("www.contoso.com").AddressList[0]; try{ tcpClient.Connect(ipAddress, 11003); } catch (Exception e ) { Console.WriteLine(e.ToString()); }
hostname
port
Exception Type | Condition |
---|---|
ArgumentNullException | The hostname parameter is null. |
ArgumentOutOfRangeException | The port parameter is not between IPEndPoint.MinPort and IPEndPoint.MaxPort. |
SocketException | An operating system error occurred while accessing the socket. |
//Uses a host name and port number to establish a socket connection. TcpClient tcpClient = new TcpClient(); try{ tcpClient.Connect("www.contoso.com", 11002); } catch (Exception e ) { Console.WriteLine(e.ToString()); }
protected virtual void Dispose( |
disposing
When the disposing parameter is true, this method releases all resources held by any managed objects that this TcpClient references. It does this by invoking the Dispose() method of each referenced object.
For more information about Dispose and Object.Finalize, see the conceptual topic at MSDN: cleaningupunmanagedresources and the conceptual topic at MSDN: overridingfinalizemethod.
// This derived class demonstrates the use of three protected methods belonging to the TcpClient class public class MyTcpClientDerivedClass : TcpClient{ // Constructor for the derived class. public MyTcpClientDerivedClass() : base(){ } public void UsingProtectedMethods(){ // Uses the protected 'Active' property belonging to the TcpClient base class // to determine if a connection is established. if (this.Active){ // Calls the protected 'Client' property belonging to the TcpClient base class. Socket s = this.Client; // Uses the Socket returned by Client to set an option that is not available using TcpClient. s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); } // To free all resources, calls the protected virtual method Dispose belonging to the TcpClient base class. this.Dispose(true); GC.SuppressFinalize(this); } }
~TcpClient(); |
public virtual int GetHashCode(); |
public NetworkStream GetStream(); |
Exception Type | Condition |
---|---|
InvalidOperationException | The TcpClient is not connected to a remote host. |
ObjectDisposedException | The TcpClient has been closed. |
TcpClient tcpClient = new TcpClient(); // Uses the GetStream public method to return the NetworkStream. try{ NetworkStream networkStream = tcpClient.GetStream(); if(networkStream.CanWrite){ Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?"); networkStream.Write(sendBytes, 0, sendBytes.Length); } else{ Console.WriteLine("You cannot write data to this stream."); tcpClient.Close(); return; } if(networkStream.CanRead){ // Reads NetworkStream into a byte buffer. byte[] bytes = new byte[tcpClient.ReceiveBufferSize]; // Read can return anything from 0 to numBytesToRead. // This method blocks until at least one byte is read. networkStream.Read(bytes, 0, (int) tcpClient.ReceiveBufferSize); // Returns the data received from the host to the console. string returndata = Encoding.ASCII.GetString(bytes); Console.WriteLine("This is what the host returned to you: " + returndata); } else{ Console.WriteLine("You cannot read data from this stream."); tcpClient.Close(); return; } } catch (Exception e ) { Console.WriteLine(e.ToString()); }
public Type GetType(); |
protected object MemberwiseClone(); |
public virtual string ToString(); |