Type: System.Net.Sockets.TcpClient System.Net.Sockets.TcpClient ClassAssembly: System.dll Namespace: System.Net.Sockets Summary Provides client connections for TCP network services. C# Syntax: public class TcpClient : IDisposable Remarks The TcpClient class builds upon the Socket class to provide TCP services at a higher level of abstraction. TcpClient provides simple methods for connecting, sending, and receiving data over a network. You can connect with a remote host using one of the following two ways: Create an instance of the TcpClient class using either no parameters, or using a local IPEndPoint, and then call one of the three available TcpClient TcpClient.Connect methods. Create an instance of the TcpClient class using the host name and port number of the device to which you intend to connect. This constructor will automatically establish your connection. 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. Notes to inheritors: You can use the Socket accessed through the TcpClient.Client to facilitate any functionality not available using the simplified interface of TcpClient property. Specifically, you can call Socket.SetSocketOption to set your desired option. Example The following example establishes a TcpClient connection using the host name www.contoso.com on port 11000. You use the underlying NetworkStream instance to send and receive simple string statements.
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());
}
See also: System.Net.Sockets Namespace | TcpListener | NetworkStream | MSDN: tcpudp System.Net.Sockets.TcpClient Member List: Public Constructors 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. Public Properties 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. Public Methods 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. Protected Properties 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. Protected Methods 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: System.Object System.Net.Sockets.TcpClient System.Net.Sockets.TcpClient Member DetailsOverloaded ctor #1 Summary Initializes a new instance of the TcpClient class. Default constructor. This constructor is called by derived class constructors to initialize state in this type. C# Syntax: public TcpClient(); Remarks The default constructor initializes a new TcpClient. You must call the TcpClient.Connect method to establish a remote host connection. Example The following example demonstrates how to use the default constructor to create a new TcpClient.
//Creates a TCPClient using the default constructor.
TcpClient tcpClientC = new TcpClient();
Return to top Overloaded ctor #2 Summary Initializes a new instance of TcpClient bound to the specified local endpoint. C# Syntax: public TcpClient( IPEndPoint localEP ); Parameters: localEP The IPEndPoint to which you bind the TCP Socket. Exceptions Exception Type Condition ArgumentNullException The localEP parameter is null. Remarks The localEP parameter specifies the local IPEndPoint. This constructor creates an underlying socket and binds that socket to localEp. You must call the TcpClient.Connect method to establish a remote host connection. Note Use this constructor if you want to specify which local network interface (IP address), and port number to use when establishing a remote host connection. Example The following example demonstrates how to create an instance of the TcpClient class using a local endpoint.
//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());
}
See also: IPEndPoint Return to top Overloaded ctor #3 Summary Initializes a new instance of the TcpClient class and connects to the specified port on the specified host. C# Syntax: public TcpClient( string hostname, int port ); Parameters: hostname DNS name of the remote host to which you intend to connect. port Port number of the remote host to which you intend to connect. Exceptions 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. Remarks This constructor initializes a new TcpClient and establishes a remote host connection by calling TcpClient.Connect using the provided hostname and port parameters. This constructor allows you to initialize, resolve the DNS host name, and connect in one convenient step. Example The following example demonstrates how to create an instance of TcpClient class using a host name and port number.
//Creates a TCPClient using hostname and port.
try{
TcpClient tcpClientB = new TcpClient("www.contoso.com", 11000);
}
catch (Exception e ) {
Console.WriteLine(e.ToString());
}
See also: TCPClient.#ctor Return to top Property: Active (read-write) Summary Gets or set a value that indicates whether a connection has been made. C# Syntax: protected bool Active {get; set;} Remarks Classes deriving from TcpClient can use this property to keep track of the underlying Socket connection state. Note TcpClient.Active can be used to avoid redundant connection attempts, or to validate operations that require a particular connection state as a pre condition. Example The following example demonstrates a derived class using the protected property TcpClient.Active. In this example, 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);
}
}
Return to top Property: Client (read-write) Summary Gets or sets the underlying Socket. C# Syntax: protected Socket Client {get; set;} Remarks TcpClient creates a Socket to send and receive data over a network. Classes deriving from TcpClient can use this property to get or set this Socket. Use the underlying Socket returned from TcpClient.Client, if you require access beyond that which TcpClient provides. You can also use TcpClient.Client to set the underlying Socket to an existing Socket. This might be useful if you want to take advantage of the simplicity of TcpClient using a pre-existing Socket. Example The following example demonstrates a derived class using the protected property TcpClient.Client. In this example, 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);
}
}
See also: Socket Return to top Property: LingerState (read-write) Summary Gets or sets information about the sockets linger time. C# Syntax: public LingerOption LingerState {get; set;} Remarks This property controls the length of time that the underlying Socket will remain open after a call to TcpClient.Close, when data remains to be sent. If the LingerOption.Enabled property of the LingerOption is true, then data will continue to be sent to the network with a time out of LingerOption.LingerTime seconds. Once the data is sent, or if the time-out expires, the connection is closed and any unsent data is lost. If the LingerOption.Enabled property of the LingerOption is false, then the connection will close, even if data remains to be sent. Example The following example sets and gets the sockets linger time.
// 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());
See also: LingerOption Return to top Property: NoDelay (read-write) Summary Gets or sets a value that enables a delay when send or receive buffers are not full. C# Syntax: public bool NoDelay {get; set;} Remarks When TcpClient.NoDelay is false, TCP does not send a packet over the network until it has collected a significant amount of outgoing data. Because of the amount of overhead in a TCP segment, sending small amounts of data would be very inefficient. However, situations do exist where you might want to send very small amounts of data or expect immediate responses from each packet you send. Your decision should weigh the relative importance of network efficiency versus application requirements. Example The following example enables the delay. It then checks the value of TcpClient.NoDelay to verify that it was successfully 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());
Return to top Property: ReceiveBufferSize (read-write) Summary Gets or sets the size of the receive buffer. C# Syntax: public int ReceiveBufferSize {get; set;} Remarks The TcpClient.ReceiveBufferSize property gets or sets the number of bytes that you are expecting to store in the receive buffer for each read operation. Note Setting this property does not limit the amount of data you can store from a single read operation. The receive buffer dynamically grows in size as space is needed to accommodate varying packet sizes. This property simply allows you to save the overhead associated with dynamic reallocation by specifying a buffer size up front. Example The following example sets and gets the receive buffer size.
// 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());
See also: TcpClient.SendBufferSize Return to top Property: ReceiveTimeout (read-write) Summary Gets or sets the amount of time a TcpClient will wait to receive data once initiated. C# Syntax: public int ReceiveTimeout {get; set;} Remarks The TcpClient.ReceiveTimeout property determines the amount of time a TcpClient will wait to receive data after a read is initiated. This time is measured in milliseconds. The underlying Socket will throw a SocketException if a read is initiated, and the TcpClient.ReceiveTimeout expires. Example The following example sets and gets the receive time out.
// 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());
Return to top Property: SendBufferSize (read-write) Summary Gets or sets the size of the send buffer. C# Syntax: public int SendBufferSize {get; set;} Remarks The TcpClient.SendBufferSize property gets or sets the number of bytes to store in the send buffer for each send operation. Note Setting this property does not limit the amount of data you can store for a single send operation. You specify the number of outgoing data bytes when using one of the underlying NetworkStream send operations. TcpClient.SendBufferSize simply allows you to save the overhead associated with dynamic reallocation by specifying a buffer size up front. Example The following example sets and gets the send buffer size.
//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());
See also: TcpClient.ReceiveBufferSize Return to top Property: SendTimeout (read-write) Summary Gets or sets the amount of time a TcpClient will wait to receive confirmation after you initiate a send. C# Syntax: public int SendTimeout {get; set;} Remarks After you initiate a send, the underlying Socket returns the number of bytes actually sent to the host. The TcpClient.SendTimeout property determines the amount of time a TcpClient will wait before receiving the number of bytes returned by the Socket class. The underlying Socket will throw a SocketException if a send is initiated and the TcpClient.SendTimeout expires. Example The following example sets and gets the TcpClient.SendTimeout value.
// 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());
Return to top Method: Close() Summary Closes the TCP connection. C# Syntax: public void Close(); Exceptions Exception Type Condition SocketException An error occurs while closing the socket. Example The following example demonstrates closing TcpClient by calling TcpClient.Close.
// Uses the Close public method to close the network stream and socket.
tcpClient.Close();
See also: Socket.Close | NetworkStream.Close Return to top Overloaded Method: Connect( IPEndPoint remoteEP ) Summary Connects the client to a remote TCP host using the specified remote network endpoint. C# Syntax: public void Connect( IPEndPoint remoteEP ); Parameters: remoteEP The IP endpoint to which you intend to connect. Exceptions Exception Type Condition ArgumentNullException The remoteEp parameter is null. SocketException An error occurred while connecting to the remote host. Remarks TcpClient.Connect establishes a TCP connection using the specified network endpoint. Before you call TcpClient.Connect, you must first create an instance of the IPEndPoint class using an IP address and a port number. This is your network endpoint. You can then call TcpClient.Connect and pass the IPEndPoint as its parameter. TcpClient.Connect then establishes a connection with the remote host by calling the Socket.Connect method of the underlying Socket. After establishing a connection, you can use TcpClient.GetStream to obtain the underlying NetworkStream. Use the underlying NetworkStream to send and receive data. Example The following example uses an IPEndPoint to connect with a 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());
}
See also: TcpClient.Connect Return to top Overloaded Method: Connect( IPAddress address, int port ) Summary Connects the client to a remote TCP host using the specified IP address and port number. C# Syntax: public void Connect( IPAddress address, int port ); Parameters: address The IP address of the host to which you intend to connect. port The port number to which you intend to connect. Exceptions 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. Remarks TcpClient.Connect establishes a TCP connection using the specified port and IP address by calling the Socket.Connect method of the underlying Socket. After establishing a connection, you can use TcpClient.GetStream to obtain the underlying NetworkStream. Use the underlying NetworkStream to send and receive data. Example The following example uses an IP Address and port number to connect with a 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());
}
See also: Socket.Connect Return to top Overloaded Method: Connect( string hostname, int port ) Summary Connects the client to the specified port on the specified host. C# Syntax: public void Connect( string hostname, int port ); Parameters: hostname The DNS name of the remote host to which you intend to connect. port The port number of the remote host to which you intend to connect. Exceptions 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. Remarks TcpClient.Connect establishes a TCP connection to the host device by calling the Socket.Connect method of the underlying Socket using the specified hostname and port number. After establishing the connection, you can use TcpClient.GetStream to obtain the underlying NetworkStream. Use the underlying NetworkStream to send and receive data. Example The following example uses the host name and port number to connect with a remote host.
//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());
}
See also: Socket.Connect Return to top Method: Dispose( bool disposing ) Summary Releases the unmanaged resources used by the TcpClient and optionally releases the managed resources. C# Syntax: protected virtual void Dispose( bool disposing ); Parameters: disposing true, to release both managed and unmanaged resources; false, to release only unmanaged resources. Remarks This method is called by the Dispose() method and the Object.Finalize method.Dispose() invokes this method with the disposing parameter set to true. Object.Finalize invokes this method with disposing set to false. 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. Notes to inheritors: Dispose can be called multiple times by other objects. When overriding Dispose(Boolean), be careful not to reference objects that have been previously disposed of in an earlier call to Dispose. For more information about how to implement Dispose(Boolean), see the conceptual topic at MSDN: implementingdisposemethod. For more information about Dispose and Object.Finalize, see the conceptual topic at MSDN: cleaningupunmanagedresources and the conceptual topic at MSDN: overridingfinalizemethod. Example The following example uses a derived class to demonstrate the TcpClient.Dispose method. Specifying true causes both managed and unmanaged resources to be released.
// 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);
}
}
Return to top Method: Equals( object obj ) Inherited See base class member description: System.Object.Equals C# Syntax: public virtual bool Equals( object obj ); For more information on members inherited from System.Object click on the link above. Return to top Overridden Method: Finalize() Summary Frees resources used by the TcpClient class. C# Syntax: ~TcpClient(); Remarks The TcpClient class finalizer calls the TcpClient.Close method to close the TCP connection, the NetworkStream, and the Socket. Return to top Method: GetHashCode() Inherited See base class member description: System.Object.GetHashCode C# Syntax: public virtual int GetHashCode(); For more information on members inherited from System.Object click on the link above. Return to top Method: GetStream() Summary Returns the stream used to send and receive data. C# Syntax: public NetworkStream GetStream(); Return Value: The underlying NetworkStream. Exceptions Exception Type Condition InvalidOperationException The TcpClient is not connected to a remote host. ObjectDisposedException The TcpClient has been closed. Remarks TcpClient.GetStream returns the underlying NetworkStream used to send and receive data. TcpClient.GetStream creates an instance of the NetworkStream class using the underlying Socket as its constructor parameter. NetworkStream inherits from the Stream, which provides a rich collection of methods and properties used to facilitate network communications. Example The following example uses TcpClient.GetStream to obtain the underlying NetworkStream. After obtaining the NetworkStream, it sends and receives using its NetworkStream.Write and NetworkStream.Read methods.
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());
}
See also: NetworkStream | Stream Return to top Method: GetType() Inherited See base class member description: System.Object.GetType C# Syntax: public Type GetType(); For more information on members inherited from System.Object click on the link above. Return to top Method: MemberwiseClone() Inherited See base class member description: System.Object.MemberwiseClone C# Syntax: protected object MemberwiseClone(); For more information on members inherited from System.Object click on the link above. Return to top Method: ToString() Inherited See base class member description: System.Object.ToString C# Syntax: public virtual string ToString(); For more information on members inherited from System.Object click on the link above. Return to top Top of page Copyright (c) 2002 Microsoft Corporation. All rights reserved.