TcpClient Class
Provides client connections for TCP network services.
Summary
The TcpClient class provides a simplified interface for synchronous and asynchronous network programming using TCP. It wraps a Socket object and handles many of the lower-level details of TCP communication, such as establishing connections, sending and receiving data, and managing the underlying socket. This class is ideal for building client applications that need to communicate with TCP servers.
Key features include:
- Easy connection establishment to a remote host and port.
- Access to the underlying
Socketfor more advanced operations. - Properties to access the network stream for sending and receiving data.
- Support for both synchronous and asynchronous operations.
Properties
Available
Gets the number of bytes of unread data from the network buffer.
Client
Gets or sets the underlying Socket for the TcpClient.
Connected
Gets a value indicating whether the TcpClient is connected to a remote host.
ExclusiveAddressUse
Gets or sets a value that indicates whether the TcpClient is using exclusive address binding.
LingerState
Gets or sets a LingerOption object that specifies whether a TcpClient will linger after the Socket.Close() method is called.
NoDelay
Gets or sets a value that indicates whether data is sent immediately on the TcpClient connection.
ReceiveBufferSize
Gets or sets the size of the buffer for socket receive operations.
ReceiveTimeout
Gets or sets the amount of time, in milliseconds, to wait for a receive operation to complete.
SendBufferSize
Gets or sets the size of the buffer for socket send operations.
SendTimeout
Gets or sets the amount of time, in milliseconds, to wait for a send operation to complete.
Ttl
Gets or sets the time-to-live value for UDP packets sent with this UdpClient.
Methods
Close()
Closes the TcpClient connection.
Connect(string hostname, int port)
Establishes a connection to a remote device.
Connect(IPAddress ipAddress, int port)
Establishes a connection to a remote device.
GetStream()
Returns the underlying network NetworkStream.
BeginConnect(...)
Begins an asynchronous request to connect to a NetworkAddress.
EndConnect(...)
Ends a pending asynchronous connection request.
Remarks
The TcpClient class simplifies TCP communication by providing an object-oriented interface. It abstracts away many of the complexities of the underlying Socket class, making it easier to write client applications. You can obtain a NetworkStream from a TcpClient instance to send and receive data.
When establishing a connection, you can use hostnames or IP addresses along with the target port. The Connected property can be used to check the status of the connection.
For asynchronous operations, methods like BeginConnect and EndConnect are available, allowing your application to remain responsive while waiting for network operations to complete.
It's important to dispose of TcpClient instances properly, typically by calling the Close() method or by using a using statement in C#. This ensures that network resources are released promptly.
using System;
using System.Net.Sockets;
using System.Text;
public class SimpleTcpClient
{
public static void 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}...");
client.Connect(serverIP, serverPort);
Console.WriteLine("Connected!");
NetworkStream stream = client.GetStream();
string messageToSend = "Hello, Server!";
byte[] data = Encoding.ASCII.GetBytes(messageToSend);
// Send data
stream.Write(data, 0, data.Length);
Console.WriteLine($"Sent: {messageToSend}");
// Receive data
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}");
}
}
catch (SocketException e)
{
Console.WriteLine($"SocketException: {e.Message}");
}
catch (Exception e)
{
Console.WriteLine($"Exception: {e.Message}");
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
Requirements
| Assembly | Framework |
|---|---|
| System.Net.Sockets.dll | .NET Framework 2.0, .NET Core 1.0, .NET Core 1.1, .NET Core 2.0, .NET Core 2.1, .NET Core 2.2, .NET Standard 1.3, .NET Standard 1.4, .NET Standard 1.6, .NET Standard 2.0, .NET Standard 2.1, .NET 5, .NET 6, .NET 7, .NET 8 |