Socket.EndAccept Socket.EndAccept Socket.EndAccept Socket.EndAccept Method

定义

异步接受传入的连接尝试。Asynchronously accepts an incoming connection attempt.

重载

EndAccept(Byte[], IAsyncResult) EndAccept(Byte[], IAsyncResult) EndAccept(Byte[], IAsyncResult) EndAccept(Byte[], IAsyncResult)

异步接受传入的连接尝试,并创建新的 Socket 对象来处理远程主机通信。Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. 此方法返回包含所传输的初始数据的缓冲区。This method returns a buffer that contains the initial data transferred.

EndAccept(IAsyncResult) EndAccept(IAsyncResult) EndAccept(IAsyncResult) EndAccept(IAsyncResult)

异步接受传入的连接尝试,并创建新的 Socket 来处理远程主机通信。Asynchronously accepts an incoming connection attempt and creates a new Socket to handle remote host communication.

EndAccept(Byte[], Int32, IAsyncResult) EndAccept(Byte[], Int32, IAsyncResult) EndAccept(Byte[], Int32, IAsyncResult) EndAccept(Byte[], Int32, IAsyncResult)

异步接受传入的连接尝试,并创建新的 Socket 对象来处理远程主机通信。Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. 此方法返回一个缓冲区,其中包含初始数据和传输的字节数。This method returns a buffer that contains the initial data and the number of bytes transferred.

EndAccept(Byte[], IAsyncResult) EndAccept(Byte[], IAsyncResult) EndAccept(Byte[], IAsyncResult) EndAccept(Byte[], IAsyncResult)

异步接受传入的连接尝试,并创建新的 Socket 对象来处理远程主机通信。Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. 此方法返回包含所传输的初始数据的缓冲区。This method returns a buffer that contains the initial data transferred.

public:
 System::Net::Sockets::Socket ^ EndAccept([Runtime::InteropServices::Out] cli::array <System::Byte> ^ % buffer, IAsyncResult ^ asyncResult);
public System.Net.Sockets.Socket EndAccept (out byte[] buffer, IAsyncResult asyncResult);
member this.EndAccept :  * IAsyncResult -> System.Net.Sockets.Socket
Public Function EndAccept (ByRef buffer As Byte(), asyncResult As IAsyncResult) As Socket

参数

buffer
Byte[]

包含所传输字节的类型 Byte 的数组。An array of type Byte that contains the bytes transferred.

asyncResult
IAsyncResult IAsyncResult IAsyncResult IAsyncResult

IAsyncResult 对象,它存储此异步操作的状态信息以及任何用户定义数据。An IAsyncResult object that stores state information for this asynchronous operation as well as any user defined data.

返回

一个 Socket 对象,它处理与远程主机的通信。A Socket object to handle communication with the remote host.

异常

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

asyncResult 并不是通过对 BeginAccept(AsyncCallback, Object) 的调用创建的。asyncResult was not created by a call to BeginAccept(AsyncCallback, Object).

尝试访问 Socket 时出错An error occurred when attempting to access the Socket

示例

下面的代码示例使用BeginAccept创建并连接套接字, 并接受前10个字节的数据。The following code example uses BeginAccept to create and connect a socket and accept the initial 10 bytes of data. 回调委托调用EndAccept以结束异步请求。The callback delegate calls EndAccept to end the asynchronous request. 传输的字节数和数据在此方法的bufferbytesTransferred参数中返回, 并显示在控制台上。The number of bytes transmitted and the data are returned in the buffer and bytesTransferred parameters of this method and are displayed on the console.

   // 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);
}

注解

EndAccept完成对的调用BeginAcceptEndAccept completes a call to BeginAccept. 在调用BeginAccept之前, 需要创建AsyncCallback由委托调用的回调方法。Before calling BeginAccept, you need to create a callback method that is invoked by the AsyncCallback delegate. 此回调方法在单独的线程中执行, 并在该BeginAccept方法返回后由系统调用。This callback method executes in a separate thread, and is called by the system after the BeginAccept method returns.

在回调方法中, 调用AsyncState asyncResult参数的方法来获取Socket正在进行连接尝试的。Within the callback method, call the AsyncState method of the asyncResult parameter to obtain the Socket on which the connection attempt is being made. 获取Socket后, 可以EndAccept调用方法以成功完成连接尝试。After obtaining the Socket, you can call the EndAccept method to successfully complete the connection attempt. buffer重载的参数包含在对的BeginAccept调用bytesTransferred中接收的数据, 参数包含在调用中传输的字节数。The buffer parameter of this overload contains the data that was received in the call to BeginAccept and the bytesTransferred parameter contains the number of bytes that were transferred in the call.

EndAccept方法会一直阻止, 直到传入连接队列中有挂起的连接。The EndAccept method blocks until a connection is pending in the incoming connection queue. 方法接受传入的连接, 并返回一个新Socket的, 它可用于向远程主机发送数据和从远程主机接收数据。 EndAcceptThe EndAccept method accepts the incoming connection and returns a new Socket that can be used to send data to and receive data from the remote host.

备注

如果收到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.

EndAccept(IAsyncResult) EndAccept(IAsyncResult) EndAccept(IAsyncResult) EndAccept(IAsyncResult)

异步接受传入的连接尝试,并创建新的 Socket 来处理远程主机通信。Asynchronously accepts an incoming connection attempt and creates a new Socket to handle remote host communication.

public:
 System::Net::Sockets::Socket ^ EndAccept(IAsyncResult ^ result);
public System.Net.Sockets.Socket EndAccept (IAsyncResult result);
member this.EndAccept : IAsyncResult -> System.Net.Sockets.Socket
Public Function EndAccept (result As IAsyncResult) As Socket

参数

asyncResult
IAsyncResult IAsyncResult IAsyncResult IAsyncResult

IAsyncResult,它存储此异步操作的状态信息以及任何用户定义数据。An IAsyncResult that stores state information for this asynchronous operation as well as any user defined data.

返回

一个 Socket,它处理与远程主机的通信。A Socket to handle communication with the remote host.

异常

asyncResult 并不是通过对 BeginAccept(AsyncCallback, Object) 的调用创建的。asyncResult was not created by a call to BeginAccept(AsyncCallback, Object).

尝试访问套接字时出错。An error occurred when attempting to access the socket. 有关详细信息,请参阅备注部分。See the Remarks section for more information.

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

示例

下面的代码示例结束异步请求, 并创建新Socket的以接受传入连接请求。The following code example ends an asynchronous request and creates a new Socket to accept an incoming connection request. 有关演示与套接字的异步通信的完整示例, 请参阅套接字代码示例For a complete example that demonstrates asynchronous communications with sockets, see Socket Code Examples.

static void Listen_Callback( IAsyncResult^ ar )
{
   allDone->Set();
   Socket^ s = safe_cast<Socket^>(ar->AsyncState);
   Socket^ s2 = s->EndAccept( ar );
   StateObject^ so2 = gcnew StateObject;
   so2->workSocket = s2;
   s2->BeginReceive( so2->buffer, 0, StateObject::BUFFER_SIZE, SocketFlags::None,
      gcnew AsyncCallback( &Async_Send_Receive::Read_Callback ), so2 );
}
public static void Listen_Callback(IAsyncResult ar){
     allDone.Set();
     Socket s = (Socket) ar.AsyncState;
     Socket s2 = s.EndAccept(ar);
     StateObject so2 = new StateObject();
     so2.workSocket = s2;
     s2.BeginReceive(so2.buffer, 0, StateObject.BUFFER_SIZE,0,
	                       new AsyncCallback(Async_Send_Receive.Read_Callback), so2);	
}
Public Shared Sub Listen_Callback(ar As IAsyncResult)
   allDone.Set()
   Dim s As Socket = CType(ar.AsyncState, Socket)
   Dim s2 As Socket = s.EndAccept(ar)
   Dim so2 As New StateObject()
   so2.workSocket = s2
   s2.BeginReceive(so2.buffer, 0, StateObject.BUFFER_SIZE, 0, New AsyncCallback(AddressOf Async_Send_Receive.Read_Callback), so2)
End Sub 'Listen_Callback

注解

EndAccept完成对的调用BeginAcceptEndAccept completes a call to BeginAccept. 在调用BeginAccept之前, 需要创建一个AsyncCallback实现委托的回调方法。Before calling BeginAccept, you need to create a callback method that implements the AsyncCallback delegate. 此回调方法在单独的线程中执行, 并在该BeginAccept方法返回后由系统调用。This callback method executes in a separate thread, and is called by the system after the BeginAccept method returns. 它必须接受BeginAcceptasyncResult方法返回的参数。It must accept the asyncResult parameter returned from the BeginAccept method.

在回调方法中, 调用AsyncState asyncResult参数的方法来获取Socket正在进行连接尝试的。Within the callback method, call the AsyncState method of the asyncResult parameter to obtain the Socket on which the connection attempt is being made. 获取Socket后, 可以EndAccept调用方法以成功完成连接尝试。After obtaining the Socket, you can call the EndAccept method to successfully complete the connection attempt.

EndAccept方法会一直阻止, 直到传入连接队列中有挂起的连接。The EndAccept method blocks until a connection is pending in the incoming connection queue. 方法接受传入的连接, 并返回一个新Socket的, 它可用于向远程主机发送数据和从远程主机接收数据。 EndAcceptThe EndAccept method accepts the incoming connection and returns a new Socket that can be used to send data to and receive data from the remote host.

备注

如果收到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.

另请参阅

EndAccept(Byte[], Int32, IAsyncResult) EndAccept(Byte[], Int32, IAsyncResult) EndAccept(Byte[], Int32, IAsyncResult) EndAccept(Byte[], Int32, IAsyncResult)

异步接受传入的连接尝试,并创建新的 Socket 对象来处理远程主机通信。Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. 此方法返回一个缓冲区,其中包含初始数据和传输的字节数。This method returns a buffer that contains the initial data and the number of bytes transferred.

public:
 System::Net::Sockets::Socket ^ EndAccept([Runtime::InteropServices::Out] cli::array <System::Byte> ^ % buffer, [Runtime::InteropServices::Out] int % bytesTransferred, IAsyncResult ^ asyncResult);
public System.Net.Sockets.Socket EndAccept (out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult);
member this.EndAccept :  *  * IAsyncResult -> System.Net.Sockets.Socket
Public Function EndAccept (ByRef buffer As Byte(), ByRef bytesTransferred As Integer, asyncResult As IAsyncResult) As Socket

参数

buffer
Byte[]

包含所传输字节的类型 Byte 的数组。An array of type Byte that contains the bytes transferred.

bytesTransferred
Int32 Int32 Int32 Int32

已传输的字节数。The number of bytes transferred.

asyncResult
IAsyncResult IAsyncResult IAsyncResult IAsyncResult

IAsyncResult 对象,它存储此异步操作的状态信息以及任何用户定义数据。An IAsyncResult object that stores state information for this asynchronous operation as well as any user defined data.

返回

一个 Socket 对象,它处理与远程主机的通信。A Socket object to handle communication with the remote host.

异常

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

asyncResult 并不是通过对 BeginAccept(AsyncCallback, Object) 的调用创建的。asyncResult was not created by a call to BeginAccept(AsyncCallback, Object).

尝试访问 Socket 时出错。An error occurred when attempting to access the Socket.

示例

下面的代码示例使用BeginAccept创建并连接套接字, 并接受前10个字节的数据。The following code example uses BeginAccept to create and connect a socket and accept the initial 10 bytes of data. 回调委托调用EndAccept以结束异步请求。The callback delegate calls EndAccept to end the asynchronous request. 传输的字节数和数据在此方法的bufferbytesTransferred参数中返回, 并显示在控制台上。The number of bytes transmitted and the data are returned in the buffer and bytesTransferred parameters of this method and are displayed on the console.

   // 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);
}

注解

EndAccept完成对的调用BeginAcceptEndAccept completes a call to BeginAccept. 在调用BeginAccept之前, 需要创建AsyncCallback由委托调用的回调方法。Before calling BeginAccept, you need to create a callback method that is invoked by the AsyncCallback delegate. 此回调方法在单独的线程中执行, 并在该BeginAccept方法返回后由系统调用。This callback method executes in a separate thread, and is called by the system after the BeginAccept method returns. 它必须接受BeginAcceptasyncResult方法返回的参数。It must accept the asyncResult parameter returned from the BeginAccept method.

在回调方法中, 调用AsyncState asyncResult参数的方法来获取Socket正在进行连接尝试的。Within the callback method, call the AsyncState method of the asyncResult parameter to obtain the Socket on which the connection attempt is being made. 获取Socket后, 可以EndAccept调用方法以成功完成连接尝试。After obtaining the Socket, you can call the EndAccept method to successfully complete the connection attempt. buffer重载的参数包含在对的BeginAccept调用bytesTransferred中接收的数据, 参数包含在调用中传输的字节数。The buffer parameter of this overload contains the data that was received in the call to BeginAccept and the bytesTransferred parameter contains the number of bytes that were transferred in the call.

EndAccept方法会一直阻止, 直到传入连接队列中有挂起的连接。The EndAccept method blocks until a connection is pending in the incoming connection queue. 方法接受传入的连接, 并返回一个新Socket的, 它可用于向远程主机发送数据和从远程主机接收数据。 EndAcceptThe EndAccept method accepts the incoming connection and returns a new Socket that can be used to send data to and receive data from the remote host.

备注

如果收到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.

适用于