TcpListener 類別

定義

接聽 TCP 網路用戶端的連接。

public ref class TcpListener
public ref class TcpListener : IDisposable
public class TcpListener
public class TcpListener : IDisposable
type TcpListener = class
type TcpListener = class
    interface IDisposable
Public Class TcpListener
Public Class TcpListener
Implements IDisposable
繼承
TcpListener
實作

範例

下列程式碼範例會建立 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 use 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 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();
  }
}
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 use 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

如需用戶端範例,請參閱 TcpClient

備註

類別 TcpListener 提供簡單的方法,可在封鎖同步模式中接聽並接受連入連線要求。 您可以使用 TcpClientSocket 來與 連線 TcpListenerTcpListener使用 IPEndPoint 、本機 IP 位址和埠號碼,或只建立埠號碼的 。 如果您想要基礎服務提供者為您指派這些值,請為本機 IP 位址指定 Any 本機 IP 位址和 0。 如果您選擇這樣做,您可以在通訊端連線之後,使用 LocalEndpoint 屬性來識別指派的資訊。

Start使用 方法來開始接聽連入連線要求。 Start 將會將連入連線排入佇列, Stop 直到您呼叫 方法或已排入佇列 MaxConnections 為止。 AcceptSocket使用 或 AcceptTcpClient 從連入連線要求佇列提取連線。 這兩種方法將會封鎖。 如果您想要避免封鎖,您可以先使用 Pending 方法來判斷佇列中是否有可用的連線要求。

Stop呼叫 方法以關閉 TcpListener

注意

方法 Stop 不會關閉任何已接受的連接。 您必須負責個別關閉這些專案。

建構函式

TcpListener(Int32)
已淘汰.
已淘汰.
已淘汰.
已淘汰.

初始化 TcpListener 類別的新執行個體,這個執行個體包含指定的設計工具。

TcpListener(IPAddress, Int32)

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

TcpListener(IPEndPoint)

使用指定的本機端點,初始化 TcpListener 類別的新執行個體。

屬性

Active

取得值,指出 TcpListener 是否正在接聽用戶端連接。

ExclusiveAddressUse

取得或設定 Boolean 值,其指定 TcpListener 是否只允許一個基礎通訊端接聽特定的通訊埠。

LocalEndpoint

取得目前 EndPointTcpListener

Server

取得基礎網路 Socket

方法

AcceptSocket()

接受暫止連接要求。

AcceptSocketAsync()

以非同步作業的方式接受暫止連接要求。

AcceptSocketAsync(CancellationToken)

接受擱置的連線要求作為可取消的非同步作業。

AcceptTcpClient()

接受暫止連接要求。

AcceptTcpClientAsync()

以非同步作業的方式接受暫止連接要求。

AcceptTcpClientAsync(CancellationToken)

接受擱置的連線要求作為可取消的非同步作業。

AllowNatTraversal(Boolean)

啟用或停用在 TcpListener 執行個體上的網路位址轉譯 (NAT) 周遊。

BeginAcceptSocket(AsyncCallback, Object)

開始非同步作業以接受連入的連接嘗試。

BeginAcceptTcpClient(AsyncCallback, Object)

開始非同步作業以接受連入的連接嘗試。

Create(Int32)

建立要在指定的連接埠上接聽的新 TcpListener 執行個體。

Dispose()

釋出目前的 TcpListener 執行個體所使用的所有資源。

EndAcceptSocket(IAsyncResult)

以非同步方式接受連入的連接嘗試,並建立新的 Socket 來處理遠端主機通訊。

EndAcceptTcpClient(IAsyncResult)

以非同步方式接受連入的連接嘗試,並建立新的 TcpClient 來處理遠端主機通訊。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Finalize()

釋放 TcpListener 類別所使用的資源。

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
Pending()

決定是否有暫止連接要求存在。

Start()

啟動對輸入連接要求的接聽。

Start(Int32)

啟動對含有最大數目暫止連接之連入連接要求的接聽。

Stop()

關閉接聽程式。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

適用於

另請參閱