TcpClient TcpClient TcpClient TcpClient Class

Definition

Provides client connections for TCP network services.

public ref class TcpClient : IDisposable
public class TcpClient : IDisposable
type TcpClient = class
    interface IDisposable
Public Class TcpClient
Implements IDisposable
Inheritance
TcpClientTcpClientTcpClientTcpClient
Implements

Examples

The following code example establishes a TcpClient connection.

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 = gcnew TcpClient( server,port );
      
      // Translate the passed message into ASCII and store it as a Byte array.
      array<Byte>^data = 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 = gcnew array<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 = Text::Encoding::ASCII->GetString( data, 0, bytes );
      Console::WriteLine( "Received: {0}", responseData );
      
      // Close everything.
      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();
}
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();
}
Shared Sub Connect(server As [String], message As [String])
   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.
      Dim port As Int32 = 13000
      Dim client As New TcpClient(server, port)
      
      ' Translate the passed message into ASCII and store it as a Byte array.
      Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
      
      ' Get a client stream for reading and writing.
      '  Stream stream = client.GetStream();
      Dim stream As NetworkStream = 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.
      Dim responseData As [String] = [String].Empty
      
      ' Read the first batch of the TcpServer response bytes.
      Dim bytes As Int32 = 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 e As ArgumentNullException
      Console.WriteLine("ArgumentNullException: {0}", e)
   Catch e As SocketException
      Console.WriteLine("SocketException: {0}", e)
   End Try
   
   Console.WriteLine(ControlChars.Cr + " Press Enter to continue...")
   Console.Read()
End Sub 'Connect

Remarks

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.

Note

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(Byte[], Int32, Int32) and Read(Byte[], Int32, Int32) methods of the NetworkStream to send and receive data with the remote host. Use the Close(Int32) method to release all resources associated with the TcpClient.

Constructors

TcpClient() TcpClient() TcpClient() TcpClient()

Initializes a new instance of the TcpClient class.

TcpClient(AddressFamily) TcpClient(AddressFamily) TcpClient(AddressFamily) TcpClient(AddressFamily)

Initializes a new instance of the TcpClient class with the specified family.

TcpClient(IPEndPoint) TcpClient(IPEndPoint) TcpClient(IPEndPoint) TcpClient(IPEndPoint)

Initializes a new instance of the TcpClient class and binds it to the specified local endpoint.

TcpClient(String, Int32) TcpClient(String, Int32) TcpClient(String, Int32) TcpClient(String, Int32)

Initializes a new instance of the TcpClient class and connects to the specified port on the specified host.

Properties

Active Active Active Active

Gets or set a value that indicates whether a connection has been made.

Available Available Available Available

Gets the amount of data that has been received from the network and is available to be read.

Client Client Client Client

Gets or sets the underlying Socket.

Connected Connected Connected Connected

Gets a value indicating whether the underlying Socket for a TcpClient is connected to a remote host.

ExclusiveAddressUse ExclusiveAddressUse ExclusiveAddressUse ExclusiveAddressUse

Gets or sets a Boolean value that specifies whether the TcpClient allows only one client to use a port.

LingerState LingerState LingerState LingerState

Gets or sets information about the linger state of the associated socket.

NoDelay NoDelay NoDelay NoDelay

Gets or sets a value that disables a delay when send or receive buffers are not full.

ReceiveBufferSize ReceiveBufferSize ReceiveBufferSize ReceiveBufferSize

Gets or sets the size of the receive buffer.

ReceiveTimeout ReceiveTimeout ReceiveTimeout ReceiveTimeout

Gets or sets the amount of time a TcpClient will wait to receive data once a read operation is initiated.

SendBufferSize SendBufferSize SendBufferSize SendBufferSize

Gets or sets the size of the send buffer.

SendTimeout SendTimeout SendTimeout SendTimeout

Gets or sets the amount of time a TcpClient will wait for a send operation to complete successfully.

Methods

BeginConnect(IPAddress, Int32, AsyncCallback, Object) BeginConnect(IPAddress, Int32, AsyncCallback, Object) BeginConnect(IPAddress, Int32, AsyncCallback, Object) BeginConnect(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).

BeginConnect(IPAddress[], Int32, AsyncCallback, Object) BeginConnect(IPAddress[], Int32, AsyncCallback, Object) BeginConnect(IPAddress[], Int32, AsyncCallback, Object) BeginConnect(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).

BeginConnect(String, Int32, AsyncCallback, Object) BeginConnect(String, Int32, AsyncCallback, Object) BeginConnect(String, Int32, AsyncCallback, Object) BeginConnect(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).

Close() Close() Close() Close()

Disposes this TcpClient instance and requests that the underlying TCP connection be closed.

Connect(IPAddress, Int32) Connect(IPAddress, Int32) Connect(IPAddress, Int32) Connect(IPAddress, Int32)

Connects the client to a remote TCP host using the specified IP address and port number.

Connect(IPAddress[], Int32) Connect(IPAddress[], Int32) Connect(IPAddress[], Int32) Connect(IPAddress[], Int32)

Connects the client to a remote TCP host using the specified IP addresses and port number.

Connect(IPEndPoint) Connect(IPEndPoint) Connect(IPEndPoint) Connect(IPEndPoint)

Connects the client to a remote TCP host using the specified remote network endpoint.

Connect(String, Int32) Connect(String, Int32) Connect(String, Int32) Connect(String, Int32)

Connects the client to the specified port on the specified host.

ConnectAsync(IPAddress, Int32) ConnectAsync(IPAddress, Int32) ConnectAsync(IPAddress, Int32) ConnectAsync(IPAddress, Int32)

Connects the client to a remote TCP host using the specified IP address and port number as an asynchronous operation.

ConnectAsync(IPAddress[], Int32) ConnectAsync(IPAddress[], Int32) ConnectAsync(IPAddress[], Int32) ConnectAsync(IPAddress[], Int32)

Connects the client to a remote TCP host using the specified IP addresses and port number as an asynchronous operation.

ConnectAsync(String, Int32) ConnectAsync(String, Int32) ConnectAsync(String, Int32) ConnectAsync(String, Int32)

Connects the client to the specified TCP port on the specified host as an asynchronous operation.

Dispose() Dispose() Dispose() Dispose()

Releases the managed and unmanaged resources used by the TcpClient.

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Releases the unmanaged resources used by the TcpClient and optionally releases the managed resources.

EndConnect(IAsyncResult) EndConnect(IAsyncResult) EndConnect(IAsyncResult) EndConnect(IAsyncResult)

Ends a pending asynchronous connection attempt.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

Frees resources used by the TcpClient class.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetStream() GetStream() GetStream() GetStream()

Returns the NetworkStream used to send and receive data.

GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

Releases all resources used by the TcpClient.

Security

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

Applies to

See also