SslStream.BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) 方法

定义

开始一个异步读操作,此操作读取流中的数据并将其存储在指定的数组中。

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

参数

buffer
Byte[]

一个 Byte 数组,该数组接收从流中读取的字节。

offset
Int32

buffer 中从零开始的位置,从此处开始存储从此流中读取的数据。

count
Int32

要从流中读取的最大字节数。

asyncCallback
AsyncCallback

AsyncCallback 委托,该委托引用读操作完成时要调用的方法。

asyncState
Object

一个用户定义的对象,其中包含读操作的相关信息。 操作完成时,此对象传递给 asyncCallback 委托。

返回

一个指示异步操作状态的 IAsyncResult 对象。

例外

buffernull

offset 小于零。

offset 大于 buffer 的长度。

offset 加上计数大于 buffer 的长度。

读操作失败。

使用了加密服务,但未能解密该数据。

已存在一个正在执行的读取操作。

此对象已关闭。

未进行身份验证。

示例

下面的代码示例演示如何启动异步读取操作。

// 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

读取完成后,将调用以下方法。

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

注解

如果启用了加密和或签名,则读取操作将从基础流读取数据、检查数据的完整性和/或解密数据。 异步读取操作必须通过调用 EndRead 方法来完成。 通常,委托会调用 asyncCallback 方法。

此方法不会在操作完成时阻止。 若要在操作完成之前阻止,请使用 Read 方法。

有关使用异步编程模型的详细信息,请参阅 异步调用同步方法

SslStream 不支持多个同时读取操作。

在成功进行身份验证之前,无法调用此方法。 若要进行身份验证,AuthenticateAsClient请调用 、 或 BeginAuthenticateAsClientAuthenticateAsServerBeginAuthenticateAsServer 方法之一。

适用于