TcpClient Class

Represents a TCP client, which provides a stream for sending and receiving data over a network using TCP.

Namespace: System.Net.Sockets

Assembly: System (in System.dll)

Syntax

public class TcpClient : IDisposable

Inheritance

System.Object
System.Net.Sockets.TcpClient

Implementations

Constructors

TcpClient()

Initializes a new instance of the TcpClient class.

public TcpClient()

TcpClient(IAsyncResult asyncResult)

Initializes a new instance of the TcpClient class with the specified asynchronous operation result.

public TcpClient(IAsyncResult asyncResult)

TcpClient(string hostname, int port)

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

public TcpClient(string hostname, int port)

TcpClient(IPEndPoint localEP)

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

public TcpClient(IPEndPoint localEP)

Properties

Client

Gets or sets the underlying socket.

public Socket Client { get; set; }

Connected

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

public bool Connected { get; }

ExclusiveAddressUse

Gets or sets a value that indicates whether the TcpClient will use exclusive address binding.

public bool ExclusiveAddressUse { get; set; }

Active

Gets or sets a value indicating whether the TcpClient is active.

public bool Active { get; set; }

Methods

Connect(string hostname, int port)

Connects this TcpClient instance to a remote device with the specified host and port.

public void Connect(string hostname, int port)

Connect(IPAddress ipAddress, int port)

Connects this TcpClient instance to a remote device identified by the specified IP address and port.

public void Connect(IPAddress ipAddress, int port)

Connect(IPEndPoint remoteEP)

Connects this TcpClient instance to a remote device identified by the specified IPEndPoint.

public void Connect(IPEndPoint remoteEP)

GetStream()

Gets the underlying network stream that communicates with the remote host.

public NetworkStream GetStream()

Close()

Closes the TcpClient connection.

public void Close()

Dispose()

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

public void Dispose()

Remarks

The TcpClient class provides a simple way to send and receive data over TCP. It wraps the Socket class and provides a higher-level abstraction.

You can use TcpClient to create TCP client applications that connect to TCP servers. The GetStream() method returns a NetworkStream object that you can use to read from and write to the network.

The TcpClient class supports asynchronous operations for connecting, sending, and receiving data, which can improve application responsiveness.

Example

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

using System;
using System.Net.Sockets;
using System.Text;

public class SimpleTcpClient
{
    public static void Main(string[] args)
    {
        try
        {
            Int32 port = 13000;
            TcpClient client = new TcpClient("localhost", port);

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

            // Translate the channel name into a byte array.
            Byte[] data = System.Text.Encoding.ASCII.GetBytes("Hello Server!");

            // Send the message to the connected TcpServer.
            stream.Write(data, 0, data.Length);
            Console.WriteLine("Sent: Hello Server!");

            // Receive the TcpServer time.
            data = new Byte[256];

            // String to store the response bytes.
            String responseData = String.Empty;

            // Read 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 exit...");
        Console.Read();
    }
}

Exceptions

System.ArgumentNullException
The hostname parameter is null.
System.ArgumentOutOfRangeException
The specified port number is not valid.
System.Net.Sockets.SocketException
An error occurred while accessing the socket. For example, an error occurred while trying to resolve the hostname.
System.ObjectDisposedException
The TcpClient has been closed or disposed.