Namespace: System.Net.Sockets
Assembly: System.Net.Primitives.dll

Class TcpClient

Provides client connections for the TCP protocol.

Public Constructors

Public Properties

Public Methods

Remarks

The TcpClient class provides a simple interface for client-side TCP service applications. You can use TcpClient to connect to a remote host, send and receive data, and close the connection. It is built on top of the Socket class, abstracting away much of the complexity of network programming.

To use TcpClient, you typically follow these steps:

  1. Create an instance of the TcpClient class.
  2. Optionally, configure properties like ReceiveBufferSize and SendBufferSize.
  3. Connect to the remote host using the Connect() or ConnectAsync() methods, specifying the hostname and port.
  4. Obtain the network stream using the GetStream() method.
  5. Use the stream to send and receive data.
  6. Close the connection by calling the Close() method.

Example

Basic TCP Client Example

This example demonstrates how to create a simple TCP client that connects to a server, sends a message, and receives a response.

C#

using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

public class SimpleTcpClient
{
    public static async Task Main(string[] args)
    {
        string serverHost = "localhost"; // Replace with your server's hostname or IP address
        int serverPort = 13000;        // Replace with your server's port

        try
        {
            using (TcpClient client = new TcpClient())
            {
                Console.WriteLine($"Connecting to {serverHost}:{serverPort}...");
                await client.ConnectAsync(serverHost, serverPort);
                Console.WriteLine("Connected!");

                NetworkStream stream = client.GetStream();

                // Send message
                string messageToSend = "Hello, Server!";
                byte[] dataToSend = Encoding.ASCII.GetBytes(messageToSend);
                await stream.WriteAsync(dataToSend, 0, dataToSend.Length);
                Console.WriteLine($"Sent: {messageToSend}");

                // Receive response
                byte[] buffer = new byte[1024];
                int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                string responseData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine($"Received: {responseData}");

                Console.WriteLine("Closing connection.");
            }
        }
        catch (SocketException socketEx)
        {
            Console.WriteLine($"SocketException: {socketEx.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
                    

Constructor Details

TcpClient()

Initializes a new instance of the TcpClient class.

C#

public TcpClient();
                

The new instance is initialized with default values.

TcpClient(AddressFamily)

Initializes a new instance of the TcpClient class and connects to the specified server using the specified address family.

C#

public TcpClient(AddressFamily addressFamily);
                

Parameters

Name Type Description
addressFamily System.Net.Sockets.AddressFamily An AddressFamily value that specifies the type of addressing to use (e.g., IPv4 or IPv6).

TcpClient(string, int)

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

C#

public TcpClient(string hostname, int port);
                

Parameters

Name Type Description
hostname string The name of the remote host.
port int The port number on the remote host to which to connect.

Property Details

Available

Gets the amount of data in the receive buffer.

C#

public int Available { get; }
                

The value returned is the number of bytes available to be read from the underlying Socket's receive buffer.

Client

Gets or sets the underlying Socket.

C#

public Socket Client { get; set; }
                

You can use this property to access advanced Socket functionality not directly exposed by TcpClient.

Connected

Gets a value indicating whether the remote host is reachable.

C#

public bool Connected { get; }
                

This property returns true if the TcpClient is successfully connected to a remote host; otherwise, false.

Method Details

Close()

Closes the connection.

C#

public void Close();
                

This method closes the connection and releases all resources associated with the TcpClient. It is equivalent to calling Dispose().

Connect(string, int)

Connects to the specified port on the specified host.

C#

public void Connect(string hostname, int port);
                

Parameters

Name Type Description
hostname string The name of the remote host.
port int The port number on the remote host to which to connect.

This method attempts to establish a TCP connection to the specified hostname and port. It blocks until the connection is established or an error occurs.

ConnectAsync(string, int)

Connects to the specified port on the specified host asynchronously.

C#

public Task ConnectAsync(string hostname, int port);
                

Parameters

Name Type Description
hostname string The name of the remote host.
port int The port number on the remote host to which to connect.

This method initiates an asynchronous connection to the specified hostname and port. It returns a Task that represents the asynchronous operation.

GetStream()

Gets the underlying network stream.

C#

public NetworkStream GetStream();
                

The NetworkStream returned by this method can be used to send and receive data over the TCP connection. It is important to dispose of the NetworkStream when you are finished with it, or when the TcpClient is disposed.

Dispose()

Releases all resources used by the TcpClient.

C#

public void Dispose();
                

This method implements the IDisposable interface and should be called when you are finished with the TcpClient to release the underlying network resources.

Dispose(bool)

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

C#

protected virtual void Dispose(bool disposing);
                

Parameters

Name Type Description
disposing bool true to release both managed and unmanaged resources; false to release only unmanaged resources.

This method is called by the public Dispose() method and the finalizer. The disposing parameter indicates whether the method was called explicitly by the user code or implicitly by the garbage collector.

See Also