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 来连接 TcpListener。 使用 TcpListenerIPEndPoint、本地 IP 地址和端口号或仅端口号Create 。 如果希望基础服务提供商为你分配这些值,请为本地 IP 地址指定 Any 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

获取当前 EndPoint 的基础 TcpListener

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)

适用于

另请参阅