Socket.EndDisconnect(IAsyncResult) Método

Definição

Encerra uma solicitação de desconexão assíncrona pendente.Ends a pending asynchronous disconnect request.

public:
 void EndDisconnect(IAsyncResult ^ asyncResult);
public void EndDisconnect (IAsyncResult asyncResult);
member this.EndDisconnect : IAsyncResult -> unit
Public Sub EndDisconnect (asyncResult As IAsyncResult)

Parâmetros

asyncResult
IAsyncResult

Um objeto IAsyncResult que armazena as informações de estado e os dados definidos pelo usuário para esta operação assíncrona.An IAsyncResult object that stores state information and any user-defined data for this asynchronous operation.

Exceções

O objeto Socket foi fechado.The Socket object has been closed.

asyncResult é null.asyncResult is null.

asyncResult não foi retornado por uma chamada ao método BeginDisconnect(Boolean, AsyncCallback, Object).asyncResult was not returned by a call to the BeginDisconnect(Boolean, AsyncCallback, Object) method.

EndDisconnect(IAsyncResult) foi chamado anteriormente para a conexão assíncrona.EndDisconnect(IAsyncResult) was previously called for the asynchronous connection.

Ocorreu um erro ao tentar acessar o soquete.An error occurred when attempting to access the socket.

A solicitação de desconexão atingiu o tempo limite.The disconnect request has timed out.

Exemplos

O exemplo de código a seguir cria um soquete para comunicação assíncrona e envia alguns dados para um host remoto.The following code example creates a socket for asynchronous communication and sends some data to a remote host. Quando os dados são enviados, Shutdown é chamado para interromper a atividade de envio e recebimento.When the data has been sent, Shutdown is called to stop the send and receive activity. Em seguida, BeginDisconnect é chamado para iniciar uma solicitação de desconexão.Then BeginDisconnect is called to begin a disconnect request. O retorno de chamada delegue chamadas EndDisconnect para encerrar a solicitação assíncrona.The callback delegate calls EndDisconnect to end the asynchronous request. Quando a solicitação for concluída, a Connected propriedade será consultada para testar se o soquete está desconectado.When the request completes, the Connected property is queried to test whether the socket is disconnected.

      // Establish the remote endpoint for the socket.
      // For this example use local computer.
      IPHostEntry^ ipHostInfo = Dns::GetHostEntry( Dns::GetHostName() );
      IPAddress^ ipAddress = ipHostInfo->AddressList[ 0 ];
      IPEndPoint^ remoteEP = gcnew IPEndPoint( ipAddress,11000 );

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

      // Connect to the remote endpoint.
      client->BeginConnect( remoteEP, gcnew AsyncCallback( ConnectCallback ), client );

      // Wait for connect.
      connectDone->WaitOne();

      // Send some data to the remote device.
      String^ data = "This is a string of data <EOF>";
      array<Byte>^buffer = Encoding::ASCII->GetBytes( data );
      client->BeginSend( buffer, 0, buffer->Length, static_cast<SocketFlags>(0), gcnew AsyncCallback( ClientSendCallback ), client );

      // Wait for send done.
      sendDone->WaitOne();

      // Release the socket.
      client->Shutdown( SocketShutdown::Both );
      client->BeginDisconnect( true, gcnew AsyncCallback( DisconnectCallback ), client );

      // Wait for the disconnect to complete.
      disconnectDone->WaitOne();
      if ( client->Connected )
            Console::WriteLine( "We're still connected" );
      else
            Console::WriteLine( "We're disconnected" );
   }

private:
   static void DisconnectCallback( IAsyncResult^ ar )
   {
      // Complete the disconnect request.
      Socket^ client = dynamic_cast<Socket^>(ar->AsyncState);
      client->EndDisconnect( ar );

      // Signal that the disconnect is complete.
      disconnectDone->Set();
   }

public:

    // Establish the remote endpoint for the socket.
    // For this example use local computer.
    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

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

    // Connect to the remote endpoint.
    client.BeginConnect(remoteEP,
        new AsyncCallback(ConnectCallback), client);

    // Wait for connect.
    connectDone.WaitOne();

    // Send some data to the remote device.
    string data = "This is a string of data <EOF>";
    byte[] buffer = Encoding.ASCII.GetBytes(data);
    client.BeginSend(buffer, 0, buffer.Length, 0, new AsyncCallback(ClientSendCallback), client);
    // Wait for send done.
    sendDone.WaitOne();

    // Release the socket.
    client.Shutdown(SocketShutdown.Both);
    client.BeginDisconnect(true, new AsyncCallback(DisconnectCallback), client);

    // Wait for the disconnect to complete.
    disconnectDone.WaitOne();
    if (client.Connected)
        Console.WriteLine("We're still connected");
    else
        Console.WriteLine("We're disconnected");
}

private static void DisconnectCallback(IAsyncResult ar)
{
    // Complete the disconnect request.
    Socket client = (Socket) ar.AsyncState;
    client.EndDisconnect(ar);

    // Signal that the disconnect is complete.
    disconnectDone.Set();
}

Comentários

EndDisconnect conclui uma chamada para BeginDisconnect .EndDisconnect completes a call to BeginDisconnect. O EndDisconnect método é bloqueado até que a desconexão seja concluída.The EndDisconnect method blocks until the disconnect completes. Para obter informações sobre operações assíncronas, consulte modelo de programação assíncrona (APM).For information about asynchronous operations, see Asynchronous Programming Model (APM).

Observação

Se você receber um SocketException , use a SocketException.ErrorCode propriedade para obter o código de erro específico.If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. Depois de obter esse código, consulte a documentação do código de erro da API do Windows Sockets versão 2 para obter uma descrição detalhada do erro.After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

Observação

Esse membro emite o rastreamento de informações quando você ativa o rastreamento de rede em seu aplicativo.This member outputs trace information when you enable network tracing in your application. Para obter mais informações, consulte rastreamento de rede em .NET Framework.For more information, see Network Tracing in .NET Framework.

Aplica-se a