SslStream.BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) Méthode
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Commence une opération de lecture asynchrone qui lit les données du flux et les stocke dans le tableau spécifié.
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);
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
Paramètres
- offset
- Int32
Emplacement de base zéro dans buffer lequel commencer à stocker les données lues à partir de ce flux.
- count
- Int32
Nombre maximal d’octets à lire à partir du flux.
- asyncCallback
- AsyncCallback
Délégué AsyncCallback qui fait référence à la méthode à appeler lorsque l’opération de lecture est terminée.
- asyncState
- Object
Objet défini par l’utilisateur qui contient des informations sur l’opération de lecture. Cet objet est transmis au asyncCallback délégué une fois l’opération terminée.
Retours
Objet IAsyncResult qui indique l’état de l’opération asynchrone.
Exceptions
buffer a la valeur null.
offset est inférieur à zéro.
-ou-
offset est supérieur à la longueur de buffer.
-ou-
offset + nombre est supérieur à la longueur de buffer.
Échec de l’opération de lecture.
-ou-
Le chiffrement est en cours d’utilisation, mais les données n’ont pas pu être déchiffrées.
Il existe déjà une opération de lecture en cours.
Cet objet a été fermé.
L’authentification n’a pas eu lieu.
Exemples
L’exemple de code suivant illustre le démarrage d’une opération de lecture asynchrone.
// 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 = (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
La méthode suivante est appelée lorsque la lecture est terminée.
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
Remarques
Si le chiffrement et ou la signature sont activés, l’opération de lecture lit les données du flux sous-jacent, vérifie l’intégrité des données et/ou les déchiffre. L’opération de lecture asynchrone doit être effectuée en appelant la EndRead méthode. En règle générale, la méthode est appelée par le asyncCallback délégué.
Cette méthode ne bloque pas pendant la fin de l’opération. Pour bloquer jusqu’à la fin de l’opération, utilisez la Read méthode.
Pour plus d’informations sur l’utilisation du modèle de programmation asynchrone, consultez Appel asynchrone de méthodes synchrones
La SslStream classe ne prend pas en charge plusieurs opérations de lecture simultanées.
Vous ne pouvez pas appeler cette méthode tant que vous n’avez pas correctement authentifié. Pour authentifier l’appel de l’une AuthenticateAsClientdes méthodes, ou BeginAuthenticateAsClient, AuthenticateAsServerBeginAuthenticateAsServer