TcpClient Class

System.Net.Sockets

Summary

Provides simple client-side implementations for the TCP protocol.

The TcpClient class provides a simplified interface to TCP network services. It uses the Socket class to communicate over a network. You can use TcpClient to create a network connection to a remote host and then send and receive data. This class also provides methods for inspecting the connection, such as checking if data is available to be read.

Syntax

public class TcpClient : IDisposable

Constructors

Properties

Methods

Methods

Accept()

protected virtual Socket Accept()

Accepts an incoming connection request.

Connect(string hostname, int port)

public virtual void Connect(string hostname, int port)

Connects to the specified port on the specified host.

Parameters:

Connect(IPEndPoint remoteEP)

public virtual void Connect(IPEndPoint remoteEP)

Connects to an IPEndPoint.

Parameters:

GetStream()

public NetworkStream GetStream()

Returns the NetworkStream associated with the TcpClient. Use this stream to send and receive data.

Returns: A NetworkStream object.

Close()

public virtual void Close()

Closes the TcpClient connection.

Constructors

TcpClient()

public TcpClient()

Initializes a new instance of the TcpClient class with default settings.

TcpClient(AddressFamily)

public TcpClient(AddressFamily addressFamily)

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

Parameters:

TcpClient(string hostname, int port)

public TcpClient(string hostname, int port)

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

Parameters:

Remarks

The TcpClient class provides a convenient way to implement client-side TCP communication. It abstracts many of the complexities of the underlying Socket class, making it easier to establish connections and exchange data.

When you need to send and receive data, obtain the NetworkStream by calling the GetStream() method. This stream provides methods like Read() and Write() for data transfer.

It is important to call the Close() method on the TcpClient when you are finished with it to release any resources held by the connection.

Example

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

public class TcpClientExample
{
    public static void Main(string[] args)
    {
        try
        {
            // Define the server's IP address and port
            string serverIp = "127.0.0.1";
            int serverPort = 13000;

            // Create a TcpClient object and connect to the server
            using (TcpClient client = new TcpClient())
            {
                Console.WriteLine($"Connecting to {serverIp}:{serverPort}...");
                client.Connect(serverIp, serverPort);
                Console.WriteLine("Connected to server!");

                // Get the network stream for sending and receiving data
                NetworkStream stream = client.GetStream();

                // Message to send to the server
                string messageToSend = "Hello, Server!";
                byte[] data = Encoding.ASCII.GetBytes(messageToSend);

                // Send data
                stream.Write(data, 0, data.Length);
                Console.WriteLine($"Sent: {messageToSend}");

                // Receive data from the server
                byte[] buffer = new byte[1024];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                string receivedMessage = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine($"Received: {receivedMessage}");

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