TcpClient and TcpListener are built on top of the System.Net.Sockets.Socket class and take care of the details of transferring data for ease of use.
1.Create a TcpClient
The TcpClient class provides TCP services at a higher level of abstraction than the Socket class. TcpClient is used to create a client connection to a remote host. Knowing how to get an IPEndPoint, let's assume you have an IPAddress to pair with your desired port number. The following example demonstrates setting up a TcpClient to connect to a time server on TCP port 13:
var ipEndPoint = new IPEndPoint(ipAddress, 13);
using TcpClient client = new();
await client.ConnectAsync(ipEndPoint);
await using NetworkStream stream = client.GetStream();
var buffer = new byte[1_024];
int received = await stream.ReadAsync(buffer);
var message = Encoding.UTF8.GetString(buffer, 0, received);
Console.WriteLine($"Message received: \"{message}\"");
// Sample output:
// Message received: "π
8/22/2022 9:07:17 AM π"
2.Create a TcpListener
The TcpListener type is used to monitor a TCP port for incoming requests and then create either a Socket or a TcpClient that manages the connection to the client. The Start method enables listening, and the Stop method disables listening on the port. The AcceptTcpClientAsync method accepts incoming connection requests and creates a TcpClient to handle the request, and the AcceptSocketAsync method accepts incoming connection requests and creates a Socket to handle the request.
The following example demonstrates creating a network time server using a TcpListener to monitor TCP port 13. When an incoming connection request is accepted, the time server responds with the current date and time from the host server.
var ipEndPoint = new IPEndPoint(IPAddress.Any, 13);
TcpListener listener = new(ipEndPoint);
try
{
listener.Start();
using TcpClient handler = await listener.AcceptTcpClientAsync();
await using NetworkStream stream = handler.GetStream();
var message = $"π
{DateTime.Now} π";
var dateTimeBytes = Encoding.UTF8.GetBytes(message);
await stream.WriteAsync(dateTimeBytes);
Console.WriteLine($"Sent message: \"{message}\"");
// Sample output:
// Sent message: "π
8/22/2022 9:07:17 AM π"
}
finally
{
listener.Stop();
}
For more information, you can check document: