TcpClient Class
System.Net.Sockets
Provides client connections for TCP network services.
Syntax
public class TcpClient : IDisposable
Remarks
The TcpClient class provides a simplified interface for using the Socket class to implement TCP services. It allows you to connect to a remote host and send or receive data.
You can use TcpClient to create client applications that connect to servers, or you can use it in conjunction with TcpListener to create server applications.
Constructors
TcpClient()
Initializes a new instance of the TcpClient class.
public TcpClient();
TcpClient(int port)
Initializes a new instance of the TcpClient class and binds it to the specified local port.
public TcpClient(int port);
Parameters
port: The local port to which the TcpClient instance will be bound.
TcpClient(string hostname, int port)
Initializes a new instance of the TcpClient class and connects it to the specified port on the specified host.
public TcpClient(string hostname, int port);
Parameters
hostname: The name of the remote host to which to connect.
port: The remote port to which to connect.
Methods
Connect(string hostname, int port)
Connects this TcpClient to a remote device as specified by the hostname and port parameters.
public void Connect(string hostname, int port);
ConnectAsync(string hostname, int port)
Connects this TcpClient to a remote device asynchronously as specified by the hostname and port parameters.
public Task ConnectAsync(string hostname, int port);
GetStream()
Returns the underlying network stream used for sending and receiving data.
public NetworkStream GetStream();
Returns
NetworkStream: A NetworkStream instance.
Dispose()
Releases all resources used by the TcpClient.
public void Dispose();
Properties
Connected
Gets a value indicating whether the TcpClient is connected to a remote host.
public bool Connected { get; }
Client
Gets or sets the underlying Socket instance.
public Socket Client { get; set; }
Example Usage
Simple TCP Client
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class SimpleTcpClient
{
public static async Task Main(string[] args)
{
string serverIp = "127.0.0.1"; // Replace with server IP
int port = 13000; // Replace with server port
try
{
using (TcpClient client = new TcpClient())
{
Console.WriteLine($"Connecting to {serverIp}:{port}...");
await client.ConnectAsync(serverIp, port);
Console.WriteLine("Connected to server.");
NetworkStream stream = client.GetStream();
byte[] data = Encoding.ASCII.GetBytes("Hello from TcpClient!");
await stream.WriteAsync(data, 0, data.Length);
Console.WriteLine("Sent: Hello from TcpClient!");
byte[] buffer = new byte[1024];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received: {response}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}