Socket.BeginAccept Socket.BeginAccept Socket.BeginAccept Socket.BeginAccept Method

定义

开始一个异步操作来接受一个传入的连接尝试。Begins an asynchronous operation to accept an incoming connection attempt.

重载

BeginAccept(AsyncCallback, Object) BeginAccept(AsyncCallback, Object) BeginAccept(AsyncCallback, Object) BeginAccept(AsyncCallback, Object)

开始一个异步操作来接受一个传入的连接尝试。Begins an asynchronous operation to accept an incoming connection attempt.

BeginAccept(Int32, AsyncCallback, Object) BeginAccept(Int32, AsyncCallback, Object) BeginAccept(Int32, AsyncCallback, Object) BeginAccept(Int32, AsyncCallback, Object)

开始异步操作以接受传入的连接尝试并接收客户端应用程序发送的第一个数据块。Begins an asynchronous operation to accept an incoming connection attempt and receives the first block of data sent by the client application.

BeginAccept(Socket, Int32, AsyncCallback, Object) BeginAccept(Socket, Int32, AsyncCallback, Object) BeginAccept(Socket, Int32, AsyncCallback, Object) BeginAccept(Socket, Int32, AsyncCallback, Object)

开始异步操作以接受从指定套接字传入的连接尝试并接收客户端应用程序发送的第一个数据块。Begins an asynchronous operation to accept an incoming connection attempt from a specified socket and receives the first block of data sent by the client application.

BeginAccept(AsyncCallback, Object) BeginAccept(AsyncCallback, Object) BeginAccept(AsyncCallback, Object) BeginAccept(AsyncCallback, Object)

开始一个异步操作来接受一个传入的连接尝试。Begins an asynchronous operation to accept an incoming connection attempt.

public:
 IAsyncResult ^ BeginAccept(AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginAccept (AsyncCallback callback, object state);
member this.BeginAccept : AsyncCallback * obj -> IAsyncResult
Public Function BeginAccept (callback As AsyncCallback, state As Object) As IAsyncResult

参数

state
Object Object Object Object

一个对象,它包含此请求的状态信息。An object that contains state information for this request.

返回

一个 IAsyncResult,它引用异步 Socket 创建。An IAsyncResult that references the asynchronous Socket creation.

异常

此方法需要 Windows NT。Windows NT is required for this method.

正在接受的套接字不会侦听连接。The accepting socket is not listening for connections. 在调用 Bind(EndPoint) 之前必须调用 Listen(Int32)BeginAccept(AsyncCallback, Object)You must call Bind(EndPoint) and Listen(Int32) before calling BeginAccept(AsyncCallback, Object).

-or- 已接受的套接字是绑定的。The accepted socket is bound.

尝试访问套接字时出错。An error occurred when attempting to access the socket.

示例

下面的代码示例尝试异步接收传入连接。The following code example attempts to receive an incoming connection asynchronously.

IPHostEntry^ lipa = Dns::Resolve( "host.contoso.com" );
IPEndPoint^ lep = gcnew IPEndPoint( lipa->AddressList[ 0 ], 11000 );

Socket^ s = gcnew Socket( lep->Address->AddressFamily,
   SocketType::Stream,
   ProtocolType::Tcp );
try
{
   s->Bind( lep );
   s->Listen( 1000 );

   while ( true )
   {
      allDone->Reset();

      Console::WriteLine( "Waiting for a connection..." );
      s->BeginAccept( gcnew AsyncCallback( &Async_Send_Receive::Connect_Callback ), s );

      allDone->WaitOne();
   }
}
catch ( Exception^ e ) 
{
   Console::WriteLine( e );
}
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);

      Socket s = new Socket(lep.Address.AddressFamily,
      	                           SocketType.Stream,
                                        ProtocolType.Tcp);
      try{
           s.Bind(lep);
           s.Listen(1000);

           while(true){
                allDone.Reset();

                Console.WriteLine("Waiting for a connection...");
                s.BeginAccept(new AsyncCallback(Async_Send_Receive.Listen_Callback), s);

                allDone.WaitOne();
           }
      }
      catch (Exception e){
           Console.WriteLine(e.ToString());
      }
   Dim lipa As IPHostEntry = Dns.Resolve("host.contoso.com")
   Dim lep As New IPEndPoint(lipa.AddressList(0), 11000)
   
   Dim s As New Socket(lep.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
   Try
      s.Bind(lep)
      s.Listen(1000)
      
      While True
         allDone.Reset()
         
         Console.WriteLine("Waiting for a connection...")
         s.BeginAccept(New AsyncCallback(AddressOf Async_Send_Receive.Listen_Callback), s)
         
         allDone.WaitOne()
      End While
   Catch e As Exception
      Console.WriteLine(e.ToString())
   End Try
End Sub 'Listen

注解

面向连接的协议可以使用BeginAccept方法异步处理传入的连接尝试。Connection-oriented protocols can use the BeginAccept method to asynchronously process incoming connection attempts. 异步接受连接使你能够在单独的执行线程中发送和接收数据。Accepting connections asynchronously gives you the ability to send and receive data within a separate execution thread. 在调用BeginAccept方法之前, 必须Listen调用方法以侦听传入连接请求并对其进行排队。Before calling the BeginAccept method, you must call the Listen method to listen for and queue incoming connection requests.

您必须创建一个实现AsyncCallback委托的回调方法, 并将其名称传递BeginAccept给方法。You must create a callback method that implements the AsyncCallback delegate and pass its name to the BeginAccept method. 为此, 必须至少通过Socket state参数将侦听对象传递给BeginAcceptTo do this, at the very minimum, you must pass the listening Socket object to BeginAccept through the state parameter. 如果回调需要更多的信息, 可以创建一个小类来保存Socket和其他所需的信息。If your callback needs more information, you can create a small class to hold the Socket and the other required information. 通过参数将此类的一个实例BeginAccept传递给方法。 statePass an instance of this class to the BeginAccept method through the state parameter.

回调方法应调用EndAccept方法。Your callback method should invoke the EndAccept method. 当应用程序调用BeginAccept时, 系统通常使用单独的线程来执行指定的回调方法, 并在EndAccept检索到挂起的连接之前将其阻止。When your application calls BeginAccept, the system usually uses a separate thread to execute the specified callback method and blocks on EndAccept until a pending connection is retrieved. EndAccept将返回一个新Socket的对象, 该对象可用于发送和接收与远程主机的数据。EndAccept will return a new Socket object that you can use to send and receive data with the remote host. 不能使用此返回Socket的来接受连接队列中的任何其他连接。You cannot use this returned Socket to accept any additional connections from the connection queue. 如果希望在调用BeginAccept方法后原始线程会被阻止, 请使用。 WaitHandle.WaitOneIf you want the original thread to block after you call the BeginAccept method, use WaitHandle.WaitOne. 当你希望原始线程继续ManualResetEvent执行时, 请在回调方法中调用的 Set 方法。Call the Set method on a ManualResetEvent in the callback method when you want the original thread to continue executing.

系统还可以使用调用线程调用回调方法。The system may also use the calling thread to invoke the callback method. 在这种情况下CompletedSynchronously , 返回IAsyncResult的上的属性将设置为指示该BeginAccept方法已同步完成。In this case, the CompletedSynchronously property on the returned IAsyncResult will be set to indicate that the BeginAccept method completed synchronously.

有关编写回调方法的其他信息, 请参阅将委托作为回调方法进行封送处理For additional information on writing callback methods see Marshaling a Delegate as a Callback Method.

若要取消挂起的BeginAccept方法调用, 请Socket关闭。To cancel a pending call to the BeginAccept method, close the Socket. 如果在异步操作过程中调用BeginAccept 方法,则会调用向方法提供的回调。CloseWhen the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginAccept method is called. EndAccept方法的后续调用将ObjectDisposedException引发, 以指示该操作已取消。A subsequent call to the EndAccept method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

备注

你可以使用RemoteEndPoint返回Socket的的属性来标识远程主机的网络地址和端口号。You can use the RemoteEndPoint property of the returned Socket to identify the remote host's network address and port number.

备注

如果收到SocketException, 请SocketException.ErrorCode使用属性获取特定的错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后, 请参阅Windows 套接字版本 2 API 错误代码文档, 以获取有关错误的详细说明。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息, 请参阅.NET Framework 中的网络跟踪For more information, see Network Tracing in the .NET Framework.

备注

为异步Socket方法缓存执行上下文 (安全上下文、模拟用户和调用上下文)。The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. 第一次使用特定的上下文 (特定的异步Socket方法、特定Socket的实例和特定的回调) 后, 该上下文的后续使用将会提高性能。After the first use of a particular context (a specific asynchronous Socket method, a specific Socket instance, and a specific callback), subsequent uses of that context will see a performance improvement.

另请参阅

BeginAccept(Int32, AsyncCallback, Object) BeginAccept(Int32, AsyncCallback, Object) BeginAccept(Int32, AsyncCallback, Object) BeginAccept(Int32, AsyncCallback, Object)

开始异步操作以接受传入的连接尝试并接收客户端应用程序发送的第一个数据块。Begins an asynchronous operation to accept an incoming connection attempt and receives the first block of data sent by the client application.

public:
 IAsyncResult ^ BeginAccept(int receiveSize, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginAccept (int receiveSize, AsyncCallback callback, object state);
member this.BeginAccept : int * AsyncCallback * obj -> IAsyncResult
Public Function BeginAccept (receiveSize As Integer, callback As AsyncCallback, state As Object) As IAsyncResult

参数

receiveSize
Int32 Int32 Int32 Int32

要从发送方读取的字节数。The number of bytes to accept from the sender.

state
Object Object Object Object

一个对象,它包含此请求的状态信息。An object that contains state information for this request.

返回

一个 IAsyncResult,它引用异步 Socket 创建。An IAsyncResult that references the asynchronous Socket creation.

异常

此方法需要 Windows NT。Windows NT is required for this method.

正在接受的套接字不会侦听连接。The accepting socket is not listening for connections. 在调用 Bind(EndPoint) 之前必须调用 Listen(Int32)BeginAccept(AsyncCallback, Object)You must call Bind(EndPoint) and Listen(Int32) before calling BeginAccept(AsyncCallback, Object).

-or- 已接受的套接字是绑定的。The accepted socket is bound.

尝试访问套接字时出错。An error occurred when attempting to access the socket.

示例

下面的代码示例打开套接字并接受异步连接。The following code example opens a socket and accepts an asynchronous connection. 在此示例中, 套接字接受前10个字节的数据。In this example, the socket accepts the initial 10 bytes of data. 回调委托将接收的字节数和数据显示在控制台上。The number of bytes received and the data are displayed on the console by the callback delegate. 有关BeginReceive如何接收剩余数据的说明, 请参阅。See BeginReceive for a description of how the remaining data is received.

   // This server waits for a connection and then uses asynchronous operations to
   // accept the connection with initial data sent from the client.
   // Establish the local endpoint for the socket.
   IPHostEntry^ ipHostInfo = Dns::GetHostEntry( Dns::GetHostName() );
   IPAddress^ ipAddress = ipHostInfo->AddressList[ 0 ];
   IPEndPoint^ localEndPoint = gcnew IPEndPoint( ipAddress,11000 );
   
   // Create a TCP/IP socket.
   Socket^ listener = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   
   // Bind the socket to the local endpoint, and listen for incoming connections.
   listener->Bind( localEndPoint );
   listener->Listen( 100 );
   for ( ; ;  )
   {
      
      // Set the event to nonsignaled state.
      allDone->Reset();
      
      // Start an asynchronous socket to listen for connections and receive data from the client.
      Console::WriteLine( "Waiting for a connection..." );
      
      // Accept the connection and receive the first 10 bytes of data.
      int receivedDataSize = 10;
      listener->BeginAccept( receivedDataSize, gcnew AsyncCallback( AcceptReceiveCallback ), listener );
      
      // Wait until a connection is made and processed before continuing.
      allDone->WaitOne();

   }
}

static void AcceptReceiveCallback( IAsyncResult^ ar )
{
   // Get the socket that handles the client request.
   Socket^ listener = dynamic_cast<Socket^>(ar->AsyncState);

   // End the operation and display the received data on the console.
   array<Byte>^Buffer;
   int bytesTransferred;
   Socket^ handler = listener->EndAccept( Buffer, bytesTransferred, ar );
   String^ stringTransferred = Encoding::ASCII->GetString( Buffer, 0, bytesTransferred );
   Console::WriteLine( stringTransferred );
   Console::WriteLine( "Size of data transferred is {0}", bytesTransferred );

   // Create the state object for the asynchronous receive.
   StateObject^ state = gcnew StateObject;
   state->workSocket = handler;
   handler->BeginReceive( state->buffer, 0, StateObject::BufferSize, static_cast<SocketFlags>(0), gcnew AsyncCallback( ReadCallback ), state );
}


    // This server waits for a connection and then uses asynchronous operations to
    // accept the connection with initial data sent from the client.
         
    
    // Establish the local endpoint for the socket.

    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
   
    // Create a TCP/IP socket.
    Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );

    // Bind the socket to the local endpoint, and listen for incoming connections.
    listener.Bind(localEndPoint);
    listener.Listen(100);

    while (true) 
    {
        // Set the event to nonsignaled state.
        allDone.Reset();

        // Start an asynchronous socket to listen for connections and receive data from the client.
        Console.WriteLine("Waiting for a connection...");

        // Accept the connection and receive the first 10 bytes of data.
        int receivedDataSize = 10;
        listener.BeginAccept(receivedDataSize, new AsyncCallback(AcceptReceiveCallback), listener);
         
        // Wait until a connection is made and processed before continuing.
        allDone.WaitOne();
    }

}


public static void AcceptReceiveCallback(IAsyncResult ar) 
{
    // Get the socket that handles the client request.
    Socket listener = (Socket) ar.AsyncState;
    
    // End the operation and display the received data on the console.
    byte[] Buffer;
    int bytesTransferred;
    Socket handler = listener.EndAccept(out Buffer, out bytesTransferred, ar);
    string stringTransferred = Encoding.ASCII.GetString(Buffer, 0, bytesTransferred);

    Console.WriteLine(stringTransferred);
    Console.WriteLine("Size of data transferred is {0}", bytesTransferred);
          
    // Create the state object for the asynchronous receive.
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
    new AsyncCallback(ReadCallback), state);
}

注解

面向连接的协议可以使用BeginAccept方法异步处理传入的连接尝试。Connection-oriented protocols can use the BeginAccept method to asynchronously process incoming connection attempts. 通过异步接受连接, 可以在单独的执行线程中发送和接收数据。Accepting connections asynchronously enables you to send and receive data within a separate execution thread. 此重载允许您在receiveSize参数中指定要在初始传输中接受的字节数。This overload allows you to specify the number of bytes to accept in the initial transfer in the receiveSize parameter.

在调用BeginAccept方法之前, 必须Listen调用方法以侦听传入连接请求并对其进行排队。Before calling the BeginAccept method, you must call the Listen method to listen for and queue incoming connection requests.

您必须创建一个实现AsyncCallback委托的回调方法, 并将其名称传递BeginAccept给方法。You must create a callback method that implements the AsyncCallback delegate and pass its name to the BeginAccept method. 为此, 必须至少通过Socket state参数将侦听对象传递给BeginAcceptTo do this, at the very minimum, you must pass the listening Socket object to BeginAccept through the state parameter. 如果回调需要更多的信息, 可以创建一个小类来保存Socket和其他所需的信息。If your callback needs more information, you can create a small class to hold the Socket and the other required information. 通过参数将此类的一个实例BeginAccept传递给方法。 statePass an instance of this class to the BeginAccept method through the state parameter.

回调方法应调用EndAccept方法。Your callback method should invoke the EndAccept method. 当应用程序调用BeginAccept时, 系统通常使用单独的线程来执行指定的回调方法, 并在EndAccept检索到挂起的连接之前将其阻止。When your application calls BeginAccept, the system usually uses a separate thread to execute the specified callback method and blocks on EndAccept until a pending connection is retrieved.

EndAccept返回一个新Socket的, 它可用于发送和接收与远程主机的数据。EndAccept returns a new Socket that you can use to send and receive data with the remote host. 不能使用此返回Socket的来接受连接队列中的任何其他连接。You cannot use this returned Socket to accept any additional connections from the connection queue. 如果希望在调用BeginAccept方法后原始线程会被阻止, 请使用。 WaitHandle.WaitOneIf you want the original thread to block after you call the BeginAccept method, use WaitHandle.WaitOne. 当你希望原始线程继续ManualResetEvent执行时, 请在回调方法中调用的 Set 方法。Call the Set method on a ManualResetEvent in the callback method when you want the original thread to continue executing.

系统还可以使用调用线程调用回调方法。The system may also use the calling thread to invoke the callback method. 在这种情况下CompletedSynchronously , 返回IAsyncResult的上的属性将设置为指示该BeginAccept方法已同步完成。In this case, the CompletedSynchronously property on the returned IAsyncResult will be set to indicate that the BeginAccept method completed synchronously.

有关编写回调方法的其他信息, 请参阅将委托作为回调方法进行封送处理For additional information on writing callback methods see Marshaling a Delegate as a Callback Method.

若要取消挂起的BeginAccept方法调用, 请Socket关闭。To cancel a pending call to the BeginAccept method, close the Socket. 如果在异步操作过程中调用BeginAccept 方法,则会调用向方法提供的回调。CloseWhen the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginAccept method is called. EndAccept方法的后续调用将ObjectDisposedException引发, 以指示该操作已取消。A subsequent call to the EndAccept method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

备注

可以调用使用RemoteEndPoint返回Socket对象的属性来标识远程主机的网络地址和端口号。You can call use the RemoteEndPoint property of the returned Socket object to identify the remote host's network address and port number.

备注

如果收到SocketException, 请SocketException.ErrorCode使用属性获取特定的错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后, 请参阅Windows 套接字版本 2 API 错误代码文档, 以获取有关错误的详细说明。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息, 请参阅.NET Framework 中的网络跟踪For more information, see Network Tracing in the .NET Framework.

备注

为异步Socket方法缓存执行上下文 (安全上下文、模拟用户和调用上下文)。The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. 第一次使用特定的上下文 (特定的异步Socket方法、特定Socket的实例和特定的回调) 后, 该上下文的后续使用将会提高性能。After the first use of a particular context (a specific asynchronous Socket method, a specific Socket instance, and a specific callback), subsequent uses of that context will see a performance improvement.

另请参阅

BeginAccept(Socket, Int32, AsyncCallback, Object) BeginAccept(Socket, Int32, AsyncCallback, Object) BeginAccept(Socket, Int32, AsyncCallback, Object) BeginAccept(Socket, Int32, AsyncCallback, Object)

开始异步操作以接受从指定套接字传入的连接尝试并接收客户端应用程序发送的第一个数据块。Begins an asynchronous operation to accept an incoming connection attempt from a specified socket and receives the first block of data sent by the client application.

public:
 IAsyncResult ^ BeginAccept(System::Net::Sockets::Socket ^ acceptSocket, int receiveSize, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginAccept (System.Net.Sockets.Socket acceptSocket, int receiveSize, AsyncCallback callback, object state);
member this.BeginAccept : System.Net.Sockets.Socket * int * AsyncCallback * obj -> IAsyncResult
Public Function BeginAccept (acceptSocket As Socket, receiveSize As Integer, callback As AsyncCallback, state As Object) As IAsyncResult

参数

acceptSocket
Socket Socket Socket Socket

接受的 Socket 对象。The accepted Socket object. 此值可为 nullThis value may be null.

receiveSize
Int32 Int32 Int32 Int32

要接收的最大字节数。The maximum number of bytes to receive.

state
Object Object Object Object

一个对象,它包含此请求的状态信息。An object that contains state information for this request.

返回

一个 IAsyncResult 对象,它引用异步 Socket 对象创建。An IAsyncResult object that references the asynchronous Socket object creation.

异常

此方法需要 Windows NT。Windows NT is required for this method.

正在接受的套接字不会侦听连接。The accepting socket is not listening for connections. 在调用 Bind(EndPoint) 之前必须调用 Listen(Int32)BeginAccept(AsyncCallback, Object)You must call Bind(EndPoint) and Listen(Int32) before calling BeginAccept(AsyncCallback, Object).

-or- 已接受的套接字是绑定的。The accepted socket is bound.

尝试访问套接字时出错。An error occurred when attempting to access the socket.

示例

下面的代码示例打开套接字并接受异步连接。The following code example opens a socket and accepts an asynchronous connection. 在此示例中, 套接字接受初始10个字节的数据acceptSocket , 参数为, 这会null强制BeginAccept方法创建已接受的套接字。In this example, the socket accepts the initial 10 bytes of data and the acceptSocket parameter is null, which forces the BeginAccept method to create the accepted socket. 回调委托将接收的字节数和数据显示在控制台上。The number of bytes received and the data are displayed on the console by the callback delegate. 有关BeginReceive如何接收剩余数据的说明, 请参阅。See BeginReceive for a description of how the remaining data is received.

   // This server waits for a connection and then uses asynchronous operations to
   // accept the connection with initial data sent from the client.
   // Establish the local endpoint for the socket.
   IPHostEntry^ ipHostInfo = Dns::GetHostEntry( Dns::GetHostName() );
   IPAddress^ ipAddress = ipHostInfo->AddressList[ 0 ];
   IPEndPoint^ localEndPoint = gcnew IPEndPoint( ipAddress,11000 );

   // Create a TCP/IP socket.
   Socket^ listener = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );

   // Bind the socket to the local endpoint, and listen for incoming connections.
   listener->Bind( localEndPoint );
   listener->Listen( 100 );
   for ( ; ;  )
   {
      // Set the event to nonsignaled state.
      allDone->Reset();

      // Start an asynchronous socket to listen for connections and receive data from the client.
      Console::WriteLine( "Waiting for a connection..." );

      // Accept the connection and receive the first 10 bytes of data. 
      // BeginAccept() creates the accepted socket.
      int receivedDataSize = 10;
      listener->BeginAccept( nullptr, receivedDataSize, gcnew AsyncCallback( AcceptReceiveDataCallback ), listener );

      // Wait until a connection is made and processed before continuing.
      allDone->WaitOne();
   }
}

static void AcceptReceiveDataCallback( IAsyncResult^ ar )
{
   // Get the socket that handles the client request.
   Socket^ listener = dynamic_cast<Socket^>(ar->AsyncState);
   
   // End the operation and display the received data on the console.
   array<Byte>^Buffer;
   int bytesTransferred;
   Socket^ handler = listener->EndAccept( Buffer, bytesTransferred, ar );
   String^ stringTransferred = Encoding::ASCII->GetString( Buffer, 0, bytesTransferred );
   Console::WriteLine( stringTransferred );
   Console::WriteLine( "Size of data transferred is {0}", bytesTransferred );
   
   // Create the state object for the asynchronous receive.
   StateObject^ state = gcnew StateObject;
   state->workSocket = handler;
   handler->BeginReceive( state->buffer, 0, StateObject::BufferSize, static_cast<SocketFlags>(0), gcnew AsyncCallback( ReadCallback ), state );
}

    // This server waits for a connection and then uses asynchronous operations to
    // accept the connection with initial data sent from the client.
               
    // Establish the local endpoint for the socket.

    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

    // Create a TCP/IP socket.
    Socket listener = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp );

    // Bind the socket to the local endpoint, and listen for incoming connections.
    listener.Bind(localEndPoint);
    listener.Listen(100);

    while (true) 
    {
        // Set the event to nonsignaled state.
        allDone.Reset();

        // Start an asynchronous socket to listen for connections and receive data from the client.
        Console.WriteLine("Waiting for a connection...");

        // Accept the connection and receive the first 10 bytes of data. 
        // BeginAccept() creates the accepted socket.
        int receivedDataSize = 10;
        listener.BeginAccept(null, receivedDataSize, new AsyncCallback(AcceptReceiveDataCallback), listener);

        // Wait until a connection is made and processed before continuing.
        allDone.WaitOne();
    }
}



public static void AcceptReceiveDataCallback(IAsyncResult ar) 
{
    // Get the socket that handles the client request.
    Socket listener = (Socket) ar.AsyncState;
    
    // End the operation and display the received data on the console.
    byte[] Buffer;
    int bytesTransferred;
    Socket handler = listener.EndAccept(out Buffer, out bytesTransferred, ar);
    string stringTransferred = Encoding.ASCII.GetString(Buffer, 0, bytesTransferred);

    Console.WriteLine(stringTransferred);
    Console.WriteLine("Size of data transferred is {0}", bytesTransferred);

    // Create the state object for the asynchronous receive.
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
    new AsyncCallback(ReadCallback), state);
}

注解

面向连接的协议可以使用BeginAccept方法异步处理传入的连接尝试。Connection-oriented protocols can use the BeginAccept method to asynchronously process incoming connection attempts. 异步接受连接使你能够在单独的执行线程中发送和接收数据。Accepting connections asynchronously gives you the ability to send and receive data within a separate execution thread. 此重载允许您在acceptSocket参数中指定已接受的套接字。This overload allows you to specify the accepted socket in the acceptSocket parameter. 如果此参数为null, 则已接受的套接字BeginAccept由方法创建。If this parameter is null, the accepted socket is created by the BeginAccept method. 可以在receiveSize参数中指定初始传输时要接受的字节数。You can specify the number of bytes to accept in the initial transfer in the receiveSize parameter.

在调用BeginAccept方法之前, 必须Listen调用方法以侦听传入连接请求并对其进行排队。Before calling the BeginAccept method, you must call the Listen method to listen for and queue incoming connection requests.

您必须创建一个实现AsyncCallback委托的回调方法, 并将其名称传递BeginAccept给方法。You must create a callback method that implements the AsyncCallback delegate and pass its name to the BeginAccept method. 为此, 必须至少通过Socket state参数将侦听对象传递给BeginAcceptTo do this, at the very minimum, you must pass the listening Socket object to BeginAccept through the state parameter. 如果回调需要更多的信息, 可以创建一个小类来保存Socket和其他所需的信息。If your callback needs more information, you can create a small class to hold the Socket and the other required information. 通过参数将此类的一个实例BeginAccept传递给方法。 statePass an instance of this class to the BeginAccept method through the state parameter.

回调方法应调用EndAccept方法。Your callback method should invoke the EndAccept method. 当应用程序调用BeginAccept时, 系统通常使用单独的线程来执行指定的回调方法, 并在EndAccept检索到挂起的连接之前将其阻止。When your application calls BeginAccept, the system usually uses a separate thread to execute the specified callback method and blocks on EndAccept until a pending connection is retrieved.

EndAccept返回一个新Socket的对象, 该对象可用于向远程主机发送和接收数据。EndAccept returns a new Socket object that you can use to send and receive data with the remote host. 不能使用此返回Socket的来接受连接队列中的任何其他连接。You cannot use this returned Socket to accept any additional connections from the connection queue. 如果希望在调用BeginAccept方法后原始线程会被阻止, 请使用。 WaitHandle.WaitOneIf you want the original thread to block after you call the BeginAccept method, use WaitHandle.WaitOne. 当你希望原始线程继续ManualResetEvent执行时, 请在回调方法中调用的 Set 方法。Call the Set method on a ManualResetEvent in the callback method when you want the original thread to continue executing.

系统还可以使用调用线程调用回调方法。The system may also use the calling thread to invoke the callback method. 在这种情况下CompletedSynchronously , 返回IAsyncResult的上的属性将设置为指示该BeginAccept方法已同步完成。In this case, the CompletedSynchronously property on the returned IAsyncResult will be set to indicate that the BeginAccept method completed synchronously.

有关编写回调方法的其他信息, 请参阅将委托作为回调方法进行封送处理For additional information on writing callback methods, see Marshaling a Delegate as a Callback Method.

若要取消挂起的BeginAccept方法调用, 请Socket关闭。To cancel a pending call to the BeginAccept method, close the Socket. 如果在异步操作过程中调用BeginAccept 方法,则会调用向方法提供的回调。CloseWhen the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginAccept method is called. EndAccept方法的后续调用将ObjectDisposedException引发, 以指示该操作已取消。A subsequent call to the EndAccept method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

备注

您可以使用RemoteEndPoint返回Socket对象的属性来标识远程主机的网络地址和端口号。You can use the RemoteEndPoint property of the returned Socket object to identify the remote host's network address and port number.

备注

如果收到SocketException, 请SocketException.ErrorCode使用属性获取特定的错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后, 请参阅Windows 套接字版本 2 API 错误代码文档, 以获取有关错误的详细说明。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息, 请参阅.NET Framework 中的网络跟踪For more information, see Network Tracing in the .NET Framework.

备注

为异步Socket方法缓存执行上下文 (安全上下文、模拟用户和调用上下文)。The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. 第一次使用特定的上下文 (特定的异步Socket方法、特定Socket的实例和特定的回调) 后, 该上下文的后续使用将会提高性能。After the first use of a particular context (a specific asynchronous Socket method, a specific Socket instance, and a specific callback), subsequent uses of that context will see a performance improvement.

另请参阅

适用于