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
- Client: Gets or sets the underlying Socket for the TcpClient.
- Connected: Gets a value that indicates whether the TcpClient is connected to a remote host.
- ExclusiveAddressUse: Gets or sets a value that indicates whether the TcpClient allows the bound Socket to be exclusively used by the application.
- LingerState: Gets or sets a LingerOption object that controls whether and for how long to linger after a Close method is called.
- NoDelay: Gets or sets a value that indicates whether the Nagle algorithm is disabled for the TcpClient.
- ReceiveBufferSize: Gets or sets the size of the buffer for incoming data.
- ReceiveTimeout: Gets or sets the amount of time (in milliseconds) that can pass before a call to Receive or ReceiveAsync will time out.
- SendBufferSize: Gets or sets the size of the buffer for outgoing data.
- SendTimeout: Gets or sets the amount of time (in milliseconds) that can pass before a call to Send or SendAsync will time out.
- Socket: Gets the Socket associated with the TcpClient.
Methods
- Accept(): Accepts an incoming connection request.
- Connect(string hostname, int port): Connects to the specified port on the specified host.
- Connect(IPEndPoint remoteEP): Connects to an IPEndPoint.
- GetStream(): Returns the NetworkStream associated with the TcpClient.
- Close(): Closes the TcpClient connection.
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:
hostname
: The name of the host to connect to.port
: The port number to connect to.
Connect(IPEndPoint remoteEP)
public virtual void Connect(IPEndPoint remoteEP)
Connects to an IPEndPoint.
Parameters:
remoteEP
: An IPEndPoint representing the remote host and port to connect to.
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:
addressFamily
: An AddressFamily value that specifies the type of addressing to use (e.g., InterNetwork for IPv4).
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:
hostname
: The name of the host to connect to.port
: The port number to connect to.
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}");
}
}
}