TcpClient Class

Provides client connections for TCP network services.

System.Object
  System.Net.Sockets.TcpClient

Namespace:  System.Net.Sockets
Assembly:  System (in System.dll)

public class TcpClient : IDisposable

The TcpClient type exposes the following members.

  NameDescription
Public methodTcpClient()Initializes a new instance of the TcpClient class.
Public methodTcpClient(AddressFamily)Initializes a new instance of the TcpClient class with the specified family.
Public methodTcpClient(IPEndPoint)Initializes a new instance of the TcpClient class and binds it to the specified local endpoint.
Public methodTcpClient(String, Int32)Initializes a new instance of the TcpClient class and connects to the specified port on the specified host.
Top

  NameDescription
Protected propertyActiveGets or set a value that indicates whether a connection has been made.
Public propertyAvailableGets the amount of data that has been received from the network and is available to be read.
Public propertyClientGets or sets the underlying Socket.
Public propertyConnectedGets a value indicating whether the underlying Socket for a TcpClient is connected to a remote host.
Public propertyExclusiveAddressUseGets or sets a Boolean value that specifies whether the TcpClient allows only one client to use a port.
Public propertyLingerStateGets or sets information about the linger state of the associated socket.
Public propertyNoDelayGets or sets a value that disables a delay when send or receive buffers are not full.
Public propertyReceiveBufferSizeGets or sets the size of the receive buffer.
Public propertyReceiveTimeoutGets or sets the amount of time a TcpClient will wait to receive data once a read operation is initiated.
Public propertySendBufferSizeGets or sets the size of the send buffer.
Public propertySendTimeoutGets or sets the amount of time a TcpClient will wait for a send operation to complete successfully.
Top

  NameDescription
Public methodBeginConnect(IPAddress, Int32, AsyncCallback, Object)Begins an asynchronous request for a remote host connection. The remote host is specified by an IPAddress and a port number (Int32).
Public methodBeginConnect(IPAddress[], Int32, AsyncCallback, Object)Begins an asynchronous request for a remote host connection. The remote host is specified by an IPAddress array and a port number (Int32).
Public methodBeginConnect(String, Int32, AsyncCallback, Object)Begins an asynchronous request for a remote host connection. The remote host is specified by a host name (String) and a port number (Int32).
Public methodCloseDisposes this TcpClient instance and requests that the underlying TCP connection be closed.
Public methodConnect(IPEndPoint)Connects the client to a remote TCP host using the specified remote network endpoint.
Public methodConnect(IPAddress, Int32)Connects the client to a remote TCP host using the specified IP address and port number.
Public methodConnect(IPAddress[], Int32)Connects the client to a remote TCP host using the specified IP addresses and port number.
Public methodConnect(String, Int32)Connects the client to the specified port on the specified host.
Public methodConnectAsync(IPAddress, Int32)Connects the client to a remote TCP host using the specified IP address and port number as an asynchronous operation.
Public methodConnectAsync(IPAddress[], Int32)Connects the client to a remote TCP host using the specified IP addresses and port number as an asynchronous operation.
Public methodConnectAsync(String, Int32)Connects the client to the specified TCP port on the specified host as an asynchronous operation.
Protected methodDisposeReleases the unmanaged resources used by the TcpClient and optionally releases the managed resources.
Public methodEndConnectEnds a pending asynchronous connection attempt.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeFrees resources used by the TcpClient class. (Overrides Object.Finalize().)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetStreamReturns the NetworkStream used to send and receive data.
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Explicit interface implemetationPrivate methodIDisposable.DisposeInfrastructure. Releases all resources used by the TcpClient.
Top

The TcpClient class provides simple methods for connecting, sending, and receiving stream data over a network in synchronous blocking mode.

In order for TcpClient to connect and exchange data, a TcpListener or Socket created with the TCP ProtocolType must be listening for incoming connection requests. You can connect to this listener in one of the following two ways:

  • Create a TcpClient and call one of the three available Connect methods.

  • Create a TcpClient using the host name and port number of the remote host. This constructor will automatically attempt a connection.

NoteNote

If you want to send connectionless datagrams in synchronous blocking mode, use the UdpClient class.

Notes to Inheritors

To send and receive data, use the GetStream method to obtain a NetworkStream. Call the Write and Read methods of the NetworkStream to send and receive data with the remote host. Use the Close method to release all resources associated with the TcpClient.

The following code example establishes a TcpClient connection.

static void Connect(String server, String message) 
{
  try 
  {
    // Create a TcpClient. 
    // Note, for this client to work you need to have a TcpServer  
    // connected to the same address as specified by the server, port 
    // combination.
    Int32 port = 13000;
    TcpClient client = new TcpClient(server, port);

    // Translate the passed message into ASCII and store it as a Byte array.
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);         

    // Get a client stream for reading and writing. 
   //  Stream stream = client.GetStream();

    NetworkStream stream = client.GetStream();

    // Send the message to the connected TcpServer. 
    stream.Write(data, 0, data.Length);

    Console.WriteLine("Sent: {0}", message);         

    // Receive the TcpServer.response. 

    // Buffer to store the response bytes.
    data = new Byte[256];

    // String to store the response ASCII representation.
    String responseData = String.Empty;

    // Read the first batch of the TcpServer response bytes.
    Int32 bytes = stream.Read(data, 0, data.Length);
    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    Console.WriteLine("Received: {0}", responseData);         

    // Close everything.
    stream.Close();         
    client.Close();         
  } 
  catch (ArgumentNullException e) 
  {
    Console.WriteLine("ArgumentNullException: {0}", e);
  } 
  catch (SocketException e) 
  {
    Console.WriteLine("SocketException: {0}", e);
  }

  Console.WriteLine("\n Press Enter to continue...");
  Console.Read();
}

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

  • SocketPermission 

    Permission to establish an outgoing connection or accept an incoming request.

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft