Class TcpClient
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
NetworkStreamfor 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()
TcpClient class.
public TcpClient(string hostname, int port)
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; }
TcpClient is connected to a remote host.
public int Available { get; }
public Socket Client { get; set; }
Socket.
public bool Connected { get; }
TcpClient.
public LingerOption LingerState { get; set; }
LingerOption object that specifies whether a TcpClient will linger after a Close call.
public bool NoDelay { get; set; }
public int ReceiveBufferSize { get; set; }
public int ReceiveTimeout { get; set; }
public int SendBufferSize { get; set; }
public int SendTimeout { get; set; }
Methods
public void Close()
TcpClient.
public void Connect(string hostname, int port)
| 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)
| 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)
| 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
| 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();
}
}