TcpClient Class

Namespace: System.Net.Sockets

Provides client connections for TCP network services. The TcpClient class simplifies the process of sending and receiving data using the Socket class.

Inheritance Hierarchy

Object
    MarshalByRefObject
        TcpClient

Remarks

The TcpClient class provides a convenient wrapper around the Socket class for implementing TCP client applications. It handles the underlying socket creation, connection establishment, and data transmission. You can access the underlying Socket object via the Client property if you need more fine-grained control.

Constructors

public TcpClient()

public TcpClient();

Initializes a new instance of the TcpClient class.

public TcpClient(string hostname, int port)

public TcpClient( string hostname, int port );

Initializes a new instance of the TcpClient class and establishes a connection to the specified host and port.

hostname: System.String

The remote host to connect to.

port: System.Int32

The remote port to connect to.

Methods

public void Close()

public void Close();

Closes the TcpClient connection.

public NetworkStream GetStream()

public NetworkStream GetStream();

Returns: System.Net.Sockets.NetworkStream

Returns the underlying network stream used for sending and receiving data.

public IAsyncResult BeginConnect(string hostname, int port, AsyncCallback requestCallback, object state)

public IAsyncResult BeginConnect( string hostname, int port, AsyncCallback requestCallback, object state );

Returns: System.IAsyncResult

Begins an asynchronous connection request to a remote host and port.

public void EndConnect(IAsyncResult asyncResult)

public void EndConnect( IAsyncResult asyncResult );

Ends a pending asynchronous connection request.

Properties

public Socket Client { get; set; }

public Socket Client { get; set; }

Gets or sets the underlying Socket object for the TcpClient.

public bool Connected { get; }

public bool Connected { get; }

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

public int ReceiveBufferSize { get; set; }

public int ReceiveBufferSize { get; set; }

Gets or sets the size of the receive buffer.

public int SendBufferSize { get; set; }

public int SendBufferSize { get; set; }

Gets or sets the size of the send buffer.

Example Usage

The following C# code demonstrates how to create a simple TCP client that connects to a server, sends a message, and receives a response.

// Assuming a TCP server is running on localhost:13000
using System;
using System.Net.Sockets;
using System.Text;

public class TcpClientExample {
    public static void Main( string[] args ) {
        string serverHost = "127.0.0.1";
        int serverPort = 13000;

        try {
            // Create a TcpClient object and connect to the server
            TcpClient client = new TcpClient(serverHost, serverPort);
            Console.WriteLine("Connected to server!");

            // Get the network stream to send and receive data
            NetworkStream stream = client.GetStream();

            // Send a message to the server
            string messageToSend = "Hello from TcpClient!";
            byte[] dataToSend = Encoding.ASCII.GetBytes(messageToSend);
            stream.Write(dataToSend, 0, dataToSend.Length);
            Console.WriteLine("Sent: " + messageToSend);

            // Receive a response from the server
            byte[] buffer = new byte[1024];
            int bytesRead = stream.Read(buffer, 0, buffer.Length);
            string responseData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received: " + responseData);

            // Close the connection
            client.Close();
            Console.WriteLine("Connection closed.");
        } catch (Exception e) {
            Console.WriteLine("Error: " + e.Message);
        }
    }
}

This example assumes you have a corresponding TCP server listening on localhost port 13000.

See Also