.NET API Documentation

Class TcpClient

Represents a client that can send and receive data using TCP.

Summary

The TcpClient class provides a simple, platform-independent implementation of the TCP client socket. It abstracts the underlying socket operations, making it easier to develop network-aware applications. You can use TcpClient to connect to a remote host, send and receive data, and disconnect from the server.

Key features include:

  • Establishing a TCP connection to a specified host and port.
  • Accessing the underlying NetworkStream for sending and receiving data.
  • Checking connection status and client availability.
  • Handling connection timeouts.

Remarks

The TcpClient class is a high-level wrapper around the Socket class, specifically for TCP communication. It simplifies the common tasks associated with establishing and managing a TCP connection. For more advanced scenarios or lower-level control, you might need to work directly with the Socket class.

When you create a TcpClient object, it does not immediately establish a connection. You must call the Connect or ConnectAsync method to initiate the connection. Once connected, you can obtain the NetworkStream associated with the client to perform read and write operations.

It is important to properly close the TcpClient connection when it is no longer needed to release network resources. This can be done by calling the Close method or by using a using statement if the TcpClient implements IDisposable.

Constructors

public TcpClient()

Initializes a new instance of the TcpClient class.

public TcpClient(string hostname, int port)

Initializes a new instance of the TcpClient class and establishes a connection to the specified server.
Name Type Description
hostname string The name of the host to which you want to connect.
port int The port number to which you want to connect.

Properties

public bool Active { get; }

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

public int Available { get; }

Gets the number of bytes available in the receive buffer.

public Socket Client { get; set; }

Gets or sets the underlying Socket.

public bool Connected { get; }

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

public LingerOption LingerState { get; set; }

Gets or sets a LingerOption object that specifies whether a TcpClient will linger after a Close call.

public bool NoDelay { get; set; }

Gets or sets a value that indicates whether the Nagle algorithm is disabled.

public int ReceiveBufferSize { get; set; }

Gets or sets the size of the receive buffer.

public int ReceiveTimeout { get; set; }

Gets or sets the time-out value, in milliseconds, for blocking send-receive operations.

public int SendBufferSize { get; set; }

Gets or sets the size of the send buffer.

public int SendTimeout { get; set; }

Gets or sets the time-out value, in milliseconds, for blocking send-receive operations.

Methods

public void Close()

Releases all resources used by the TcpClient.

public void Connect(string hostname, int port)

Establishes a connection to a remote TCP host.
Name Type Description
hostname string The name of the host to which you want to connect.
port int The port number to which you want to connect.

public void Connect(IPAddress ipAddress, int port)

Establishes a connection to a remote TCP host.
Name Type Description
ipAddress IPAddress The IPAddress of the remote host.
port int The port number to which you want to connect.

public async Task ConnectAsync(string hostname, int port)

Asynchronously establishes a connection to a remote TCP host.
Name Type Description
hostname string The name of the host to which you want to connect.
port int The port number to which you want to connect.

public NetworkStream GetStream()

Returns the underlying network stream.

Returns

Type Description
NetworkStream A NetworkStream object that can be used to send and receive data.

Example

The following example demonstrates how to create a TcpClient, connect to a server, send a message, and receive a response.

using System; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; public class TcpClientExample { public static async Task Main(string[] args) { string serverIp = "127.0.0.1"; // Replace with your server IP int serverPort = 13000; // Replace with your server port try { using (TcpClient client = new TcpClient()) { Console.WriteLine($"Connecting to {serverIp}:{serverPort}..."); await client.ConnectAsync(serverIp, serverPort); Console.WriteLine("Connected!"); NetworkStream stream = client.GetStream(); string messageToSend = "Hello, Server!"; byte[] dataToSend = Encoding.ASCII.GetBytes(messageToSend); await stream.WriteAsync(dataToSend, 0, dataToSend.Length); Console.WriteLine($"Sent: {messageToSend}"); 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}"); } } catch (SocketException socketEx) { Console.WriteLine($"SocketException: {socketEx.Message}"); } catch (Exception ex) { Console.WriteLine($"Exception: {ex.Message}"); } Console.WriteLine("Press any key to exit."); Console.ReadKey(); } }