TcpListener.EndAcceptSocket(IAsyncResult) Método

Definición

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

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

Parámetros

asyncResult
IAsyncResult

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

Devoluciones

Socket

Objeto Socket.A Socket.

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

Excepciones

El objeto Socket subyacente se ha cerrado.The underlying Socket has been closed.

El parámetro asyncResult es null.The asyncResult parameter is null.

El parámetro asyncResult no se creó mediante una llamada al método BeginAcceptSocket(AsyncCallback, Object).The asyncResult parameter was not created by a call to the BeginAcceptSocket(AsyncCallback, Object) method.

El método EndAcceptSocket(IAsyncResult) se definió previamente.The EndAcceptSocket(IAsyncResult) method was previously called.

Se ha producido un error al intentar obtener acceso al Socket.An error occurred while attempting to access the Socket.

Ejemplos

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

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

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

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

        // Accept the connection.
        // BeginAcceptSocket() creates the accepted socket.
        listener->BeginAcceptSocket(
            gcnew AsyncCallback(DoAcceptSocketCallback), listener);
        // Wait until a connection is made and processed before
        // continuing.
        ClientConnected->WaitOne();
    }

    // Process the client connection.
public:
    static void DoAcceptSocketCallback(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.
        Socket^ clientSocket = listener->EndAcceptSocket(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.
        ClientConnected->Set();
    }
// Thread signal.
public static ManualResetEvent clientConnected =
    new ManualResetEvent(false);

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

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

    // Accept the connection.
    // BeginAcceptSocket() creates the accepted socket.
    listener.BeginAcceptSocket(
        new AsyncCallback(DoAcceptSocketCallback), listener);
    // Wait until a connection is made and processed before
    // continuing.
    clientConnected.WaitOne();
}

// Process the client connection.
public static void DoAcceptSocketCallback(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.
    Socket clientSocket = listener.EndAcceptSocket(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.
    clientConnected.Set();
}
' Thread signal.
Public Shared clientConnected As New ManualResetEvent(False)


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


' Process the client connection.
Public Shared Sub DoAcceptSocketCallback(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 clientSocket As Socket = listener.EndAcceptSocket(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.
   clientConnected.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 AcceptSocket método.To perform this operation synchronously, use the AcceptSocket method.

Nota

Puede llamar a la RemoteEndPoint propiedad del devuelto Socket para identificar la dirección de red y el número de puerto del host remoto.You can call the RemoteEndPoint property of the returned Socket 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