TcpListener Class
The System.Net.Sockets.TcpListener
class is used to listen for incoming TCP connections from client applications. It provides a simple way to create a TCP server that can accept connections on a specific IP address and port.
Overview
TcpListener
operates by binding to a local endpoint (an IP address and a port number) and then waiting for clients to connect to that endpoint. When a connection request arrives, the TcpListener
accepts it and returns a TcpClient
object that represents the connection to the client.
Key Features:
- Listens for incoming TCP connections.
- Binds to a specific IP address and port.
- Asynchronous and synchronous operation modes.
- Accepts connections and provides
TcpClient
instances.
Syntax
public class TcpListener : MarshalByRefObject
Constructors
TcpListener
has several constructors to define how it listens for connections:
TcpListener(IPAddress localaddr, int port)
Initializes a new instance of the TcpListener
class that listens on the specified IP address and port.
localaddr
: AnIPAddress
object that specifies the local IP address to bind to.port
: The port number on which to listen.
TcpListener(int port)
Initializes a new instance of the TcpListener
class that listens on the specified port and the local computer's default IP address.
port
: The port number on which to listen.
TcpListener(IPEndPoint localEP)
Initializes a new instance of the TcpListener
class with the specified IPEndPoint
.
localEP
: AnIPEndPoint
object that specifies the local IP address and port to bind to.
Methods
Method Name | Description |
---|---|
Start() |
Starts listening for incoming connection requests. |
Stop() |
Stops listening for incoming connection requests. |
AcceptTcpClient() |
Accepts an incoming connection request and returns a TcpClient object used to send and receive data. This is a blocking call. |
AcceptTcpClientAsync() |
Asynchronously accepts an incoming connection request and returns a Task<TcpClient> representing the asynchronous operation. |
Pending() |
Returns a boolean value indicating whether there are any pending connection requests. |
Server.LocalEndPoint |
Gets the local endpoint to which the listener is bound. |
Example Usage
This example demonstrates how to create a simple TCP server that listens for connections and echoes back any data received from clients.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class SimpleTcpServer
{
public static void Main(string[] args)
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
// Start listening for connections.
server.Start();
Console.WriteLine($"Server started. Listening on port {port}...");
// Enter the listening loop.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
// Handle the connection in a separate thread to allow multiple clients.
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
catch (SocketException e)
{
Console.WriteLine($"SocketException: {e}");
}
finally
{
// Stop listening when done.
server?.Stop();
Console.WriteLine("Server stopped.");
}
}
public static void HandleClientComm(object clientObj)
{
TcpClient tcpClient = (TcpClient)clientObj;
NetworkStream stream = null;
try
{
stream = tcpClient.GetStream();
byte[] bytes = new byte[256];
int i;
// Loop to receive all data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a UTF8 string.
string data = Encoding.UTF8.GetString(bytes, 0, i);
Console.WriteLine($"Received: {data}");
// Process the data sent by the client.
// For this example, we'll just echo it back.
byte[] msg = Encoding.UTF8.GetBytes(data.ToUpper());
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine($"Sent: {Encoding.UTF8.GetString(msg)}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error handling client: {ex.Message}");
}
finally
{
// Shutdown and remove the TcpClient instance.
stream?.Close();
tcpClient.Close();
Console.WriteLine("Client disconnected.");
}
}
}
Note on Blocking vs. Asynchronous Operations
AcceptTcpClient()
is a blocking method. The thread calling it will pause until a client connects. For applications that need to remain responsive or handle many clients concurrently, AcceptTcpClientAsync()
is recommended.