TcpListener.EndAcceptTcpClient(IAsyncResult) Método

Definición

Acepta asincrónicamente un intento de conexión entrante y crea un nuevo objeto TcpClient para controlar la comunicación con el host remoto.Asynchronously accepts an incoming connection attempt and creates a new TcpClient to handle remote host communication.

public:
 System::Net::Sockets::TcpClient ^ EndAcceptTcpClient(IAsyncResult ^ asyncResult);
public System.Net.Sockets.TcpClient EndAcceptTcpClient (IAsyncResult asyncResult);
member this.EndAcceptTcpClient : IAsyncResult -> System.Net.Sockets.TcpClient
Public Function EndAcceptTcpClient (asyncResult As IAsyncResult) As TcpClient

Parámetros

asyncResult
IAsyncResult

Interfaz IAsyncResult que se devuelve al llamar al método BeginAcceptTcpClient(AsyncCallback, Object).An IAsyncResult returned by a call to the BeginAcceptTcpClient(AsyncCallback, Object) method.

Devoluciones

TcpClient

Objeto TcpClient.A TcpClient.

Objeto TcpClient que se utiliza para enviar y recibir datos.The TcpClient used to send and receive data.

Ejemplos

En el ejemplo de código siguiente se muestra el uso del BeginAcceptTcpClient método para crear y conectar un socket.The following code example demonstrates the use of the BeginAcceptTcpClient method to create and connect a socket. El delegado de devolución de llamada llama al EndAcceptTcpClient método para finalizar la solicitud asincrónica.The callback delegate calls the EndAcceptTcpClient method to end the asynchronous request.

    // Thread signal.
public:
    static ManualResetEvent^ TcpClientConnected;

    // Accept one client connection asynchronously.
public:
    static void DoBeginAcceptTcpClient(TcpListener^ listener)
    {
        // Set the event to nonsignaled state.
        TcpClientConnected->Reset();

        // Start to listen for connections from a client.
        Console::WriteLine("Waiting for a connection...");

        // Accept the connection.
        // BeginAcceptSocket() creates the accepted socket.
        listener->BeginAcceptTcpClient(
            gcnew AsyncCallback(DoAcceptTcpClientCallback),
            listener);

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

    // Process the client connection.
public:
    static void DoAcceptTcpClientCallback(IAsyncResult^ result)
    {
        // Get the listener that handles the client request.
        TcpListener^ listener = (TcpListener^) result->AsyncState;

        // End the operation and display the received data on
        // the console.
        TcpClient^ client = listener->EndAcceptTcpClient(result);

        // Process the connection here. (Add the client to a
        // server table, read data, etc.)
        Console::WriteLine("Client connected completed");

        // Signal the calling thread to continue.
        TcpClientConnected->Set();

    }
// Thread signal.
public static ManualResetEvent tcpClientConnected =
    new ManualResetEvent(false);

// Accept one client connection asynchronously.
public static void DoBeginAcceptTcpClient(TcpListener
    listener)
{
    // Set the event to nonsignaled state.
    tcpClientConnected.Reset();

    // Start to listen for connections from a client.
    Console.WriteLine("Waiting for a connection...");

    // Accept the connection.
    // BeginAcceptSocket() creates the accepted socket.
    listener.BeginAcceptTcpClient(
        new AsyncCallback(DoAcceptTcpClientCallback),
        listener);

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

// Process the client connection.
public static void DoAcceptTcpClientCallback(IAsyncResult ar)
{
    // Get the listener that handles the client request.
    TcpListener listener = (TcpListener) ar.AsyncState;

    // End the operation and display the received data on
    // the console.
    TcpClient client = listener.EndAcceptTcpClient(ar);

    // Process the connection here. (Add the client to a
    // server table, read data, etc.)
    Console.WriteLine("Client connected completed");

    // Signal the calling thread to continue.
    tcpClientConnected.Set();
}
' Thread signal.
Public Shared tcpClientConnected As New ManualResetEvent(False)


' Accept one client connection asynchronously.
Public Shared Sub DoBeginAcceptTcpClient(listener As TcpListener)
   ' Set the event to nonsignaled state.
   tcpClientConnected.Reset()
   
   ' Start to listen for connections from a client.
   Console.WriteLine("Waiting for a connection...")
   
   ' Accept the connection. 
   ' BeginAcceptSocket() creates the accepted socket.
   listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf DoAcceptTcpClientCallback), listener)
   
   ' Wait until a connection is made and processed before 
   ' continuing.
   tcpClientConnected.WaitOne()
End Sub


' Process the client connection.
Public Shared Sub DoAcceptTcpClientCallback(ar As IAsyncResult)
   ' Get the listener that handles the client request.
   Dim listener As TcpListener = CType(ar.AsyncState, TcpListener)
   
   ' End the operation and display the received data on 
   ' the console.
   Dim client As TcpClient = listener.EndAcceptTcpClient(ar)
   
   ' Process the connection here. (Add the client to a
   ' server table, read data, etc.)
   Console.WriteLine("Client connected completed")
   
   ' Signal the calling thread to continue.
   tcpClientConnected.Set()
End Sub
 

Comentarios

Este método se bloquea hasta que se completa la operación.This method blocks until the operation is complete. Para realizar esta operación sincrónicamente, use el AcceptTcpClient método.To perform this operation synchronously, use the AcceptTcpClient method.

Nota

Puede llamar a la RemoteEndPoint propiedad del socket subyacente ( Client ) para identificar la dirección de red y el número de puerto del host remoto.You can call the RemoteEndPoint property of the underlying socket (Client) to identify the remote host's network address and port number.

Nota

Si recibe un SocketException , use la SocketException.ErrorCode propiedad para obtener el código de error específico y consulte la documentación del código de error de la API de Windows Sockets versión 2 para obtener una descripción detallada del error.If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code and refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

Nota

Este miembro genera información de seguimiento cuando se habilita el seguimiento de red en la aplicación.This member outputs trace information when you enable network tracing in your application. Para obtener más información, consulte seguimiento de red en el .NET Framework.For more information, see Network Tracing in the .NET Framework.

Se aplica a