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 来连接 TcpListenerYou 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

获取当前 EndPoint 的基础 TcpListenerGets 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.

适用于

另请参阅