TcpClient Class
System.Net.Sockets.TcpClient
Provides client connections for TCP network services.
Namespace: System.Net.Sockets
Assembly: System.Net.Primitives.dll
Inheritance: Object > MarshalByRefObject > TcpClient
Constructors
TcpClient()
Initializes a new instance of the TcpClient class.
TcpClient(Int32)
Initializes a new instance of the TcpClient class and connects to the specified port on the local host.
Parameters:
portToConnect: The port to which you want to connect.
TcpClient(String, Int32)
Initializes a new instance of the TcpClient class and connects to the specified host and port.
Parameters:
hostname: The name of the remote host to which to connect.port: The port to which you want to connect.
Properties
Active
Gets a value that indicates whether the TcpClient is connected to a remote host.
Client
Gets or sets the underlying Socket.
ExclusiveAddressUse
Gets or sets a value that indicates whether the TcpClient allows the bound Socket to be bound to an exclusive local IPAddress.
LingerState
Gets or sets a LingerOption for this TcpClient.
NoDelay
Gets or sets a value that indicates whether the Nagle algorithm is disabled for this TcpClient.
ReceiveBufferSize
Gets or sets the size of the buffer used for receiving data.
ReceiveTimeout
Gets or sets the amount of time a synchronous receive operation will block before timing out.
SendBufferSize
Gets or sets the size of the buffer used for sending data.
SendTimeout
Gets or sets the amount of time a synchronous send operation will block before timing out.
Methods
Close()
Closes the TcpClient connection.
Connect(String, Int32)
Connects to the specified TCP port on the specified host.
Parameters:
hostname: The name of the remote host to which to connect.port: The port to which you want to connect.
Connect(IPAddress, Int32)
Connects to the specified TCP port on the specified IP address.
Parameters:
address: AnIPAddressinstance representing the remote host.port: The port to which you want to connect.
GetStream()
Returns the NetworkStream used for sending and receiving data.
Remarks
The TcpClient class provides a simple way to send and receive data over a network using TCP. It wraps the Socket class, offering a more user-friendly interface for common client-side operations.
To establish a connection, you can use one of the Connect methods or specify the host and port in the constructor. Once connected, you can obtain a NetworkStream using the GetStream method to read from and write to the network.
Important considerations include setting appropriate timeouts for receive and send operations to prevent indefinite blocking, and managing the client's lifecycle by calling Close when it is no longer needed.