SslStream.BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) Método

Definición

Inicia una operación de lectura asincrónica que lee los datos de la secuencia y los almacena en la matriz especificada.Begins an asynchronous read operation that reads data from the stream and stores it in the specified array.

public:
 override IAsyncResult ^ BeginRead(cli::array <System::Byte> ^ buffer, int offset, int count, AsyncCallback ^ asyncCallback, System::Object ^ asyncState);
public override IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState);
public override IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState);
override this.BeginRead : byte[] * int * int * AsyncCallback * obj -> IAsyncResult
Public Overrides Function BeginRead (buffer As Byte(), offset As Integer, count As Integer, asyncCallback As AsyncCallback, asyncState As Object) As IAsyncResult

Parámetros

buffer
Byte[]

Matriz Byte que recibe los bytes leídos de la secuencia.A Byte array that receives the bytes read from the stream.

offset
Int32

Posición de base cero de buffer donde se comienzan a almacenar los datos leídos de esta secuencia.The zero-based location in buffer at which to begin storing the data read from this stream.

count
Int32

Número máximo de bytes que se van a leer de la secuencia.The maximum number of bytes to read from the stream.

asyncCallback
AsyncCallback

Delegado de AsyncCallback que hace referencia al método que se va a invocar una vez finalizada la operación de lectura.An AsyncCallback delegate that references the method to invoke when the read operation is complete.

asyncState
Object

Objeto definido por el usuario que contiene información sobre la operación de lectura.A user-defined object that contains information about the read operation. Este objeto se pasa al delegado de asyncCallback cuando la operación ha terminado.This object is passed to the asyncCallback delegate when the operation completes.

Devoluciones

IAsyncResult

Un objeto IAsyncResult que indica el estado de la operación asincrónica.An IAsyncResult object that indicates the status of the asynchronous operation.

Excepciones

buffer es null.buffer is null.

offset es menor que cero.offset is less than zero.

O bien-or-

offset es mayor que la longitud de buffer.offset is greater than the length of buffer.

O bien-or- La suma de offset y el recuento es mayor que la longitud de buffer.offset + count is greater than the length of buffer.

Se ha producido un error en la operación de lectura.The read operation failed.

O bien-or-

El cifrado está en uso, pero los datos no se pudieron descifrar.Encryption is in use, but the data could not be decrypted.

Ya hay una operación de lectura en curso.There is already a read operation in progress.

Este objeto se ha cerrado.This object has been closed.

No se ha producido la autenticación.Authentication has not occurred.

Ejemplos

En el ejemplo de código siguiente se muestra cómo iniciar una operación de lectura asincrónica.The following code example demonstrates starting an asynchronous read operation.

// readData and buffer holds the data read from the server.
// They is used by the ReadCallback method.
static StringBuilder^ readData = gcnew StringBuilder;
static array<Byte>^buffer = gcnew array<Byte>(2048);

// readData and buffer holds the data read from the server.
// They is used by the ReadCallback method.
static StringBuilder readData = new StringBuilder();
static byte [] buffer = new byte[2048];
' readData and buffer holds the data read from the server.
' They is used by the ReadCallback method.
Shared readData As New StringBuilder()
Shared buffer As Byte() = New Byte(2048) {}
static void WriteCallback( IAsyncResult^ ar )
{
   SslStream^ stream = dynamic_cast<SslStream^>(ar->AsyncState);
   try
   {
      Console::WriteLine( L"Writing data to the server." );
      stream->EndWrite( ar );
      
      // Asynchronously read a message from the server.
      stream->BeginRead( buffer, 0, buffer->Length, gcnew AsyncCallback( ReadCallback ), stream );
   }
   catch ( Exception^ writeException ) 
   {
      e = writeException;
      complete = true;
      return;
   }

}


static void WriteCallback(IAsyncResult ar)
{
    SslStream stream = (SslStream) ar.AsyncState;
    try
    {
        Console.WriteLine("Writing data to the server.");
        stream.EndWrite(ar);
        // Asynchronously read a message from the server.
        stream.BeginRead(buffer, 0, buffer.Length,
            new AsyncCallback(ReadCallback),
            stream);
    }
    catch (Exception writeException)
    {
        e = writeException;
        complete = true;
        return;
    }
}
Shared Sub WriteCallback(ar As IAsyncResult)
    Dim stream = CType(ar.AsyncState, SslStream)
    Try
        Console.WriteLine("Writing data to the server.")
        stream.EndWrite(ar)
        ' Asynchronously read a message from the server.
        stream.BeginRead(buffer, 0, buffer.Length, New AsyncCallback(AddressOf ReadCallback), stream)
    Catch writeException As Exception
        e = writeException
        complete = True
        Return
    End Try
End Sub

Cuando se completa la lectura, se llama al método siguiente.The following method is called when the read completes.

static void ReadCallback( IAsyncResult^ ar )
{
   
   // Read the  message sent by the server.
   // The end of the message is signaled using the
   // "<EOF>" marker.
   SslStream^ stream = dynamic_cast<SslStream^>(ar->AsyncState);
   int byteCount = -1;
   try
   {
      Console::WriteLine( L"Reading data from the server." );
      byteCount = stream->EndRead( ar );
      
      // Use Decoder class to convert from bytes to UTF8
      // in case a character spans two buffers.
      Decoder^ decoder = Encoding::UTF8->GetDecoder();
      array<Char>^chars = gcnew array<Char>(decoder->GetCharCount( buffer, 0, byteCount ));
      decoder->GetChars( buffer, 0, byteCount, chars, 0 );
      readData->Append( chars );
      
      // Check for EOF or an empty message.
      if ( readData->ToString()->IndexOf( L"<EOF>" ) == -1 && byteCount != 0 )
      {
         
         // We are not finished reading.
         // Asynchronously read more message data from  the server.
         stream->BeginRead( buffer, 0, buffer->Length, gcnew AsyncCallback( ReadCallback ), stream );
      }
      else
      {
         Console::WriteLine( L"Message from the server: {0}", readData );
      }
   }
   catch ( Exception^ readException ) 
   {
      e = readException;
      complete = true;
      return;
   }

   complete = true;
}



static void ReadCallback(IAsyncResult ar)
{
    // Read the  message sent by the server.
    // The end of the message is signaled using the
    // "<EOF>" marker.
    SslStream stream = (SslStream) ar.AsyncState;
    int byteCount = -1;
    try
    {
        Console.WriteLine("Reading data from the server.");
        byteCount = stream.EndRead(ar);
        // Use Decoder class to convert from bytes to UTF8
        // in case a character spans two buffers.
        Decoder decoder = Encoding.UTF8.GetDecoder();
        char[] chars = new char[decoder.GetCharCount(buffer,0, byteCount)];
        decoder.GetChars(buffer, 0, byteCount, chars,0);
        readData.Append (chars);
        // Check for EOF or an empty message.
        if (readData.ToString().IndexOf("<EOF>") == -1 && byteCount != 0)
        {
            // We are not finished reading.
            // Asynchronously read more message data from  the server.
            stream.BeginRead(buffer, 0, buffer.Length,
                new AsyncCallback(ReadCallback),
                stream);
        }
        else
        {
            Console.WriteLine("Message from the server: {0}", readData.ToString());
        }
    }
    catch (Exception readException)
    {
        e = readException;
        complete = true;
        return;
    }
    complete = true;
}

Shared Sub ReadCallback(ar As IAsyncResult)
    ' Read the  message sent by the server.
    ' The end of the message is signaled using the
    ' "<EOF>" marker.
    Dim stream = CType(ar.AsyncState, SslStream)
    Dim byteCount As Integer
    Try
        Console.WriteLine("Reading data from the server.")
        byteCount = stream.EndRead(ar)
        ' Use Decoder class to convert from bytes to UTF8
        ' in case a character spans two buffers.
        Dim decoder As Decoder = Encoding.UTF8.GetDecoder()
        Dim chars = New Char(decoder.GetCharCount(buffer, 0, byteCount)) {}
        decoder.GetChars(buffer, 0, byteCount, chars, 0)
        readData.Append(chars)
        ' Check for EOF or an empty message.
        If readData.ToString().IndexOf("<EOF>") = -1 AndAlso byteCount <> 0 Then
            ' We are not finished reading.
            ' Asynchronously read more message data from  the server.
            stream.BeginRead(buffer, 0, buffer.Length, New AsyncCallback(AddressOf ReadCallback), stream)
        Else
            Console.WriteLine("Message from the server: {0}", readData.ToString())
        End If
    Catch readException As Exception
        e = readException
        complete = True
        Return
    End Try
    complete = True
End Sub

Comentarios

Si está habilitado el cifrado o la firma, la operación de lectura Lee los datos de la secuencia subyacente, comprueba la integridad de los datos o los descifra.If encryption and or signing are enabled, the read operation reads the data from the underlying stream, checks the integrity of the data, and/or decrypts it. La operación de lectura asincrónica se debe completar llamando al EndRead método.The asynchronous read operation must be completed by calling the EndRead method. Normalmente, el delegado invoca el método asyncCallback .Typically, the method is invoked by the asyncCallback delegate.

Este método no se bloquea mientras se completa la operación.This method does not block while the operation completes. Para bloquear hasta que finalice la operación, use el Read método.To block until the operation completes, use the Read method.

Para obtener información detallada sobre el uso del modelo de programación asincrónica, consulte llamar a métodos sincrónicos de forma asincrónicaFor detailed information about using the asynchronous programming model, see Calling Synchronous Methods Asynchronously

La SslStream clase no admite varias operaciones de lectura simultáneas.The SslStream class does not support multiple simultaneous read operations.

No se puede llamar a este método hasta que se haya autenticado correctamente.You cannot call this method until you have successfully authenticated. Para autenticar, llame a uno de los AuthenticateAsClient métodos, o BeginAuthenticateAsClient , AuthenticateAsServer BeginAuthenticateAsServer .To authenticate call one of the AuthenticateAsClient, or BeginAuthenticateAsClient, AuthenticateAsServer, BeginAuthenticateAsServer methods.

Se aplica a