Edit

Share via


TcpListener Class

Definition

Listens for connections from TCP network clients.

C#
public class TcpListener
C#
public class TcpListener : IDisposable
Inheritance
TcpListener
Implements

Examples

The following code example creates a TcpListener.

C#
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

class MyTcpListener
{
  public static void Main()
  {
    TcpListener server = null;
    try
    {
      // Set the TcpListener on port 13000.
      Int32 port = 13000;
      IPAddress localAddr = IPAddress.Parse("127.0.0.1");

      // TcpListener server = new TcpListener(port);
      server = new TcpListener(localAddr, port);

      // Start listening for client requests.
      server.Start();

      // Buffer for reading data
      Byte[] bytes = new Byte[256];
      String data = null;

      // Enter the listening loop.
      while(true)
      {
        Console.Write("Waiting for a connection... ");

        // Perform a blocking call to accept requests.
        // You could also use server.AcceptSocket() here.
        using TcpClient client = server.AcceptTcpClient();
        Console.WriteLine("Connected!");

        data = null;

        // Get a stream object for reading and writing
        NetworkStream stream = client.GetStream();

        int i;

        // Loop to receive all the data sent by the client.
        while((i = stream.Read(bytes, 0, bytes.Length))!=0)
        {
          // Translate data bytes to a ASCII string.
          data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
          Console.WriteLine("Received: {0}", data);

          // Process the data sent by the client.
          data = data.ToUpper();

          byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

          // Send back a response.
          stream.Write(msg, 0, msg.Length);
          Console.WriteLine("Sent: {0}", data);
        }
      }
    }
    catch(SocketException e)
    {
      Console.WriteLine("SocketException: {0}", e);
    }
    finally
    {
      server.Stop();
    }

    Console.WriteLine("\nHit enter to continue...");
    Console.Read();
  }
}

See TcpClient for a client example.

Remarks

The TcpListener class provides simple methods that listen for and accept incoming connection requests in blocking synchronous mode. You can use either a TcpClient or a Socket to connect with a TcpListener. Create a TcpListener using an IPEndPoint, a Local IP address and port number, or just a port number. Specify Any for the local IP address and 0 for the local port number if you want the underlying service provider to assign those values for you. If you choose to do this, you can use the LocalEndpoint property to identify the assigned information, after the socket has connected.

Use the Start method to begin listening for incoming connection requests. Start will queue incoming connections until you either call the Stop method or it has queued MaxConnections. Use either AcceptSocket or AcceptTcpClient to pull a connection from the incoming connection request queue. These two methods will block. If you want to avoid blocking, you can use the Pending method first to determine if connection requests are available in the queue.

Call the Stop method to close the TcpListener.

Note

The Stop method does not close any accepted connections. You are responsible for closing these separately.

Constructors

TcpListener(Int32)
Obsolete.
Obsolete.
Obsolete.
Obsolete.

Initializes a new instance of the TcpListener class that listens on the specified port.

TcpListener(IPAddress, Int32)

Initializes a new instance of the TcpListener class that listens for incoming connection attempts on the specified local IP address and port number.

TcpListener(IPEndPoint)

Initializes a new instance of the TcpListener class with the specified local endpoint.

Properties

Active

Gets a value that indicates whether TcpListener is actively listening for client connections.

ExclusiveAddressUse

Gets or sets a Boolean value that specifies whether the TcpListener allows only one underlying socket to listen to a specific port.

LocalEndpoint

Gets the underlying EndPoint of the current TcpListener.

Server

Gets the underlying network Socket.

Methods

AcceptSocket()

Accepts a pending connection request.

AcceptSocketAsync()

Accepts a pending connection request as an asynchronous operation.

AcceptSocketAsync(CancellationToken)

Accepts a pending connection request as a cancellable asynchronous operation.

AcceptTcpClient()

Accepts a pending connection request.

AcceptTcpClientAsync()

Accepts a pending connection request as an asynchronous operation.

AcceptTcpClientAsync(CancellationToken)

Accepts a pending connection request as a cancellable asynchronous operation.

AllowNatTraversal(Boolean)

Enables or disables Network Address Translation (NAT) traversal on a TcpListener instance.

BeginAcceptSocket(AsyncCallback, Object)

Begins an asynchronous operation to accept an incoming connection attempt.

BeginAcceptTcpClient(AsyncCallback, Object)

Begins an asynchronous operation to accept an incoming connection attempt.

Create(Int32)

Creates a new TcpListener instance to listen on the specified port.

Dispose()

Releases all resources used by the current TcpListener instance.

EndAcceptSocket(IAsyncResult)

Asynchronously accepts an incoming connection attempt and creates a new Socket to handle remote host communication.

EndAcceptTcpClient(IAsyncResult)

Asynchronously accepts an incoming connection attempt and creates a new TcpClient to handle remote host communication.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize()

Frees resources used by the TcpListener class.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
Pending()

Determines if there are pending connection requests.

Start()

Starts listening for incoming connection requests.

Start(Int32)

Starts listening for incoming connection requests with a maximum number of pending connection.

Stop()

Closes the listener.

ToString()

Returns a string that represents the current object.

(Inherited from Object)

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

See also