Assembly: System.Net.Primitives.dll
Class TcpClient
Provides client connections for the TCP protocol.
Public Constructors
-
TcpClient()
Initializes a new instance of the TcpClient class.
-
TcpClient(AddressFamily)
Initializes a new instance of the TcpClient class and connects to the specified server using the specified address family.
-
TcpClient(string, int)
Initializes a new instance of the TcpClient class and connects to the specified server on the specified port.
Public Properties
-
Available
Gets the amount of data in the receive buffer.
-
Client
Gets or sets the underlying Socket.
-
Connected
Gets a value indicating whether the remote host is reachable.
-
ExclusiveAddressUse
Gets or sets a value that indicates whether the TcpClient is configured to allow the server to accept only one client.
-
Lasterror
Gets the last error that occurred.
-
ReceiveBuffer
Gets the size of the receive buffer.
-
ReceiveBufferSize
Gets or sets the size of the receive buffer.
-
SendBuffer
Gets the size of the send buffer.
-
SendBufferSize
Gets or sets the size of the send buffer.
-
UsageData
Gets or sets a string containing client-specific data.
Public Methods
-
Close()
Closes the connection.
-
Connect(string, int)
Connects to the specified port on the specified host.
-
ConnectAsync(string, int)
Connects to the specified port on the specified host asynchronously.
-
GetStream()
Gets the underlying network stream.
-
Dispose()
Releases all resources used by the TcpClient.
-
Dispose(bool)
Releases the unmanaged resources used by the TcpClient and optionally releases the managed resources.
Remarks
The TcpClient class provides a simple interface for client-side TCP service applications. You can use TcpClient to connect to a remote host, send and receive data, and close the connection. It is built on top of the Socket class, abstracting away much of the complexity of network programming.
To use TcpClient, you typically follow these steps:
- Create an instance of the
TcpClientclass. - Optionally, configure properties like
ReceiveBufferSizeandSendBufferSize. - Connect to the remote host using the
Connect()orConnectAsync()methods, specifying the hostname and port. - Obtain the network stream using the
GetStream()method. - Use the stream to send and receive data.
- Close the connection by calling the
Close()method.
Example
Basic TCP Client Example
This 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;
using System.Threading.Tasks;
public class SimpleTcpClient
{
public static async Task Main(string[] args)
{
string serverHost = "localhost"; // Replace with your server's hostname or IP address
int serverPort = 13000; // Replace with your server's port
try
{
using (TcpClient client = new TcpClient())
{
Console.WriteLine($"Connecting to {serverHost}:{serverPort}...");
await client.ConnectAsync(serverHost, serverPort);
Console.WriteLine("Connected!");
NetworkStream stream = client.GetStream();
// Send message
string messageToSend = "Hello, Server!";
byte[] dataToSend = Encoding.ASCII.GetBytes(messageToSend);
await stream.WriteAsync(dataToSend, 0, dataToSend.Length);
Console.WriteLine($"Sent: {messageToSend}");
// Receive response
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}");
Console.WriteLine("Closing connection.");
}
}
catch (SocketException socketEx)
{
Console.WriteLine($"SocketException: {socketEx.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Constructor Details
TcpClient()
Initializes a new instance of the TcpClient class.
public TcpClient();
The new instance is initialized with default values.
TcpClient(AddressFamily)
Initializes a new instance of the TcpClient class and connects to the specified server using the specified address family.
public TcpClient(AddressFamily addressFamily);
Parameters
| Name | Type | Description |
|---|---|---|
addressFamily |
System.Net.Sockets.AddressFamily |
An AddressFamily value that specifies the type of addressing to use (e.g., IPv4 or IPv6). |
TcpClient(string, int)
Initializes a new instance of the TcpClient class and connects to the specified server on the specified port.
public TcpClient(string hostname, int port);
Parameters
| Name | Type | Description |
|---|---|---|
hostname |
string |
The name of the remote host. |
port |
int |
The port number on the remote host to which to connect. |
Property Details
Available
Gets the amount of data in the receive buffer.
public int Available { get; }
The value returned is the number of bytes available to be read from the underlying Socket's receive buffer.
Client
Gets or sets the underlying Socket.
public Socket Client { get; set; }
You can use this property to access advanced Socket functionality not directly exposed by TcpClient.
Connected
Gets a value indicating whether the remote host is reachable.
public bool Connected { get; }
This property returns true if the TcpClient is successfully connected to a remote host; otherwise, false.
Method Details
Close()
Closes the connection.
public void Close();
This method closes the connection and releases all resources associated with the TcpClient. It is equivalent to calling Dispose().
Connect(string, int)
Connects to the specified port on the specified host.
public void Connect(string hostname, int port);
Parameters
| Name | Type | Description |
|---|---|---|
hostname |
string |
The name of the remote host. |
port |
int |
The port number on the remote host to which to connect. |
This method attempts to establish a TCP connection to the specified hostname and port. It blocks until the connection is established or an error occurs.
ConnectAsync(string, int)
Connects to the specified port on the specified host asynchronously.
public Task ConnectAsync(string hostname, int port);
Parameters
| Name | Type | Description |
|---|---|---|
hostname |
string |
The name of the remote host. |
port |
int |
The port number on the remote host to which to connect. |
This method initiates an asynchronous connection to the specified hostname and port. It returns a Task that represents the asynchronous operation.
GetStream()
Gets the underlying network stream.
public NetworkStream GetStream();
The NetworkStream returned by this method can be used to send and receive data over the TCP connection. It is important to dispose of the NetworkStream when you are finished with it, or when the TcpClient is disposed.
Dispose()
Releases all resources used by the TcpClient.
public void Dispose();
This method implements the IDisposable interface and should be called when you are finished with the TcpClient to release the underlying network resources.
Dispose(bool)
Releases the unmanaged resources used by the TcpClient and optionally releases the managed resources.
protected virtual void Dispose(bool disposing);
Parameters
| Name | Type | Description |
|---|---|---|
disposing |
bool |
true to release both managed and unmanaged resources; false to release only unmanaged resources. |
This method is called by the public Dispose() method and the finalizer. The disposing parameter indicates whether the method was called explicitly by the user code or implicitly by the garbage collector.