TcpListener 類別

定義

接聽 TCP 網路用戶端的連接。Listens for connections from TCP network clients.

public ref class TcpListener
public class TcpListener
type TcpListener = class
Public Class TcpListener
繼承
TcpListener

範例

下列程式碼範例會建立 TcpListenerThe following code example creates a TcpListener.

#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Text;
using namespace System::Threading;
void main()
{
   try
   {
      
      // Set the TcpListener on port 13000.
      Int32 port = 13000;
      IPAddress^ localAddr = IPAddress::Parse( "127.0.0.1" );
      
      // TcpListener* server = new TcpListener(port);
      TcpListener^ server = gcnew TcpListener( localAddr,port );
      
      // Start listening for client requests.
      server->Start();
      
      // Buffer for reading data
      array<Byte>^bytes = gcnew array<Byte>(256);
      String^ data = nullptr;
      
      // Enter the listening loop.
      while ( true )
      {
         Console::Write( "Waiting for a connection... " );
         
         // Perform a blocking call to accept requests.
         // You could also user server.AcceptSocket() here.
         TcpClient^ client = server->AcceptTcpClient();
         Console::WriteLine( "Connected!" );
         data = nullptr;
         
         // Get a stream Object* for reading and writing
         NetworkStream^ stream = client->GetStream();
         Int32 i;
         
         // Loop to receive all the data sent by the client.
         while ( i = stream->Read( bytes, 0, bytes->Length ) )
         {
            
            // Translate data bytes to a ASCII String*.
            data = Text::Encoding::ASCII->GetString( bytes, 0, i );
            Console::WriteLine( "Received: {0}", data );
            
            // Process the data sent by the client.
            data = data->ToUpper();
            array<Byte>^msg = Text::Encoding::ASCII->GetBytes( data );
            
            // Send back a response.
            stream->Write( msg, 0, msg->Length );
            Console::WriteLine( "Sent: {0}", data );
         }
         
         // Shutdown and end connection
         client->Close();
      }
   }
   catch ( SocketException^ e ) 
   {
      Console::WriteLine( "SocketException: {0}", e );
   }

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


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 user server.AcceptSocket() here.
        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);            
        }
         
        // Shutdown and end connection
        client.Close();
      }
    }
    catch(SocketException e)
    {
      Console.WriteLine("SocketException: {0}", e);
    }
    finally
    {
       // Stop listening for new clients.
       server.Stop();
    }

      
    Console.WriteLine("\nHit enter to continue...");
    Console.Read();
  }   
}
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Text

Class MyTcpListener

    Public Shared Sub Main()

    Dim server As TcpListener
    server=nothing
        Try
            ' Set the TcpListener on port 13000.
         Dim port As Int32 = 13000
         Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1")

         server = New TcpListener(localAddr, port)
         
         ' Start listening for client requests.
         server.Start()
         
         ' Buffer for reading data
            Dim bytes(1024) As Byte
            Dim data As String = Nothing
         
         ' Enter the listening loop.
         While True
            Console.Write("Waiting for a connection... ")
            
            ' Perform a blocking call to accept requests.
            ' You could also user server.AcceptSocket() here.
            Dim client As TcpClient = server.AcceptTcpClient()
            Console.WriteLine("Connected!")
            
            data = Nothing
            
            ' Get a stream object for reading and writing
            Dim stream As NetworkStream = client.GetStream()
            
            Dim i As Int32
            
            ' Loop to receive all the data sent by the client.
            i = stream.Read(bytes, 0, bytes.Length)
            While (i <> 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()
                    Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
               
               ' Send back a response.
               stream.Write(msg, 0, msg.Length)
                    Console.WriteLine("Sent: {0}", data)
              
               i = stream.Read(bytes, 0, bytes.Length)

            End While
            
            ' Shutdown and end connection
            client.Close()
         End While
      Catch e As SocketException
         Console.WriteLine("SocketException: {0}", e)
      Finally
         server.Stop()
      End Try
      
      Console.WriteLine(ControlChars.Cr + "Hit enter to continue....")
      Console.Read()
   End Sub

End Class

如需用戶端範例,請參閱 TcpClientSee TcpClient for a client example.

備註

TcpListener 類別提供簡單的方法,可在封鎖的同步模式下接聽並接受傳入的連接要求。The TcpListener class provides simple methods that listen for and accept incoming connection requests in blocking synchronous mode. 您可以使用 TcpClientSocket 來與 TcpListener進行連接。You can use either a TcpClient or a Socket to connect with a TcpListener. 使用 IPEndPoint、本機 IP 位址和埠號碼,或只是埠號碼來建立 TcpListenerCreate a TcpListener using an IPEndPoint, a Local IP address and port number, or just a port number. 如果您想要讓基礎服務提供者為您指派這些值,請指定本機 IP 位址的 Any,以及0作為本機埠號碼。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. 如果您選擇這樣做,則可以在通訊端連線之後,使用 LocalEndpoint 屬性來識別指派的資訊。If you choose to do this, you can use the LocalEndpoint property to identify the assigned information, after the socket has connected.

使用 Start 方法來開始接聽傳入的連線要求。Use the Start method to begin listening for incoming connection requests. Start 將會將傳入的連線排入佇列,直到您呼叫 Stop 方法或其已佇列的 MaxConnections為止。Start will queue incoming connections until you either call the Stop method or it has queued MaxConnections. 請使用 AcceptSocketAcceptTcpClient,從連入連線要求佇列提取連線。Use either AcceptSocket or AcceptTcpClient to pull a connection from the incoming connection request queue. 這兩種方法將會封鎖。These two methods will block. 如果您想要避免封鎖,您可以先使用 Pending 方法,判斷佇列中是否有連接要求。If you want to avoid blocking, you can use the Pending method first to determine if connection requests are available in the queue.

呼叫 Stop 方法以關閉 TcpListenerCall the Stop method to close the TcpListener.

注意

Stop 方法不會關閉任何已接受的連接。The Stop method does not close any accepted connections. 您必須負責個別關閉這些程式。You are responsible for closing these separately.

建構函式

TcpListener(Int32)

初始化 TcpListener 類別的新執行個體,這個執行個體包含指定的設計工具。Initializes a new instance of the TcpListener class that listens on the specified port.

TcpListener(IPAddress, Int32)

初始化 TcpListener 類別的新執行個體,這個執行個體會在指定的本機 IP 位址和通訊埠編號上接聽連入的連接嘗試。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)

使用指定的本機端點,初始化 TcpListener 類別的新執行個體。Initializes a new instance of the TcpListener class with the specified local endpoint.

屬性

Active

取得值,指出 TcpListener 是否正在接聽用戶端連接。Gets a value that indicates whether TcpListener is actively listening for client connections.

ExclusiveAddressUse

取得或設定 Boolean 值,其指定 TcpListener 是否只允許一個基礎通訊端接聽特定的通訊埠。Gets or sets a Boolean value that specifies whether the TcpListener allows only one underlying socket to listen to a specific port.

LocalEndpoint

取得目前 EndPointTcpListenerGets the underlying EndPoint of the current TcpListener.

Server

取得基礎網路 SocketGets the underlying network Socket.

方法

AcceptSocket()

接受暫止連接要求。Accepts a pending connection request.

AcceptSocketAsync()

以非同步作業的方式接受暫止連接要求。Accepts a pending connection request as an asynchronous operation.

AcceptTcpClient()

接受暫止連接要求。Accepts a pending connection request.

AcceptTcpClientAsync()

以非同步作業的方式接受暫止連接要求。Accepts a pending connection request as an asynchronous operation.

AllowNatTraversal(Boolean)

啟用或停用在 TcpListener 執行個體上的網路位址轉譯 (NAT) 周遊。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)

建立要在指定的連接埠上接聽的新 TcpListener 執行個體。Creates a new TcpListener instance to listen on the specified port.

EndAcceptSocket(IAsyncResult)

以非同步方式接受連入的連接嘗試,並建立新的 Socket 來處理遠端主機通訊。Asynchronously accepts an incoming connection attempt and creates a new Socket to handle remote host communication.

EndAcceptTcpClient(IAsyncResult)

以非同步方式接受連入的連接嘗試,並建立新的 TcpClient 來處理遠端主機通訊。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.

(繼承來源 Object)
Finalize()

釋放 TcpListener 類別所使用的資源。Frees resources used by the TcpListener class.

GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 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.

(繼承來源 Object)

安全性

SocketPermission
建立連出連線或接受傳入要求。to establish an outgoing connection or accept an incoming request.

適用於

另請參閱