NegotiateStream.BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object) Método
Definição
public:
override IAsyncResult ^ BeginWrite(cli::array <System::Byte> ^ buffer, int offset, int count, AsyncCallback ^ asyncCallback, System::Object ^ asyncState);
public override IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState);
public override IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState);
override this.BeginWrite : byte[] * int * int * AsyncCallback * obj -> IAsyncResult
Public Overrides Function BeginWrite (buffer As Byte(), offset As Integer, count As Integer, asyncCallback As AsyncCallback, asyncState As Object) As IAsyncResult
Parâmetros
- buffer
- Byte[]
Uma matriz Byte que fornece os bytes a serem gravados no fluxo.A Byte array that supplies the bytes to be written to the stream.
- offset
- Int32
O local baseado em zero em buffer no qual será iniciada a leitura dos bytes a serem gravados no fluxo.The zero-based location in buffer at which to begin reading bytes to be written to the stream.
- count
- Int32
Um valor Int32 que especifica o número de bytes a serem lidos de buffer.An Int32 value that specifies the number of bytes to read from buffer.
- asyncCallback
- AsyncCallback
Um delegado AsyncCallback que referencia o método a ser invocado quando a operação de gravação for concluída.An AsyncCallback delegate that references the method to invoke when the write operation is complete.
- asyncState
- Object
Um objeto definido pelo usuário que contém informações sobre a operação de gravação.A user-defined object containing information about the write operation. Esse objeto é passado para o representante asyncCallback quando a operação é concluída.This object is passed to the asyncCallback delegate when the operation completes.
Retornos
Um objeto IAsyncResult que indica o status da operação assíncrona.An IAsyncResult object indicating the status of the asynchronous operation.
Exceções
buffer é null.buffer is null.
offset is less than 0.offset is less than 0.
- ou --or-
offset é maior que o comprimento do buffer.offset is greater than the length of buffer.
- ou --or-
offset mais a contagem é maior que o comprimento de buffer.offset plus count is greater than the length of buffer.
A operação de gravação falhou.The write operation failed.
- ou --or-
A criptografia está em uso, mas não foi possível criptografar os dados.Encryption is in use, but the data could not be encrypted.
Já existe uma operação de gravação em andamento.There is already a write operation in progress.
Este objeto foi fechado.This object has been closed.
A autenticação não ocorreu.Authentication has not occurred.
Exemplos
O exemplo a seguir demonstra o início de uma operação de gravação assíncrona.The following example demonstrates beginning an asynchronous write operation.
// Request authentication.
NetworkStream^ clientStream = client->GetStream();
NegotiateStream^ authStream = gcnew NegotiateStream( clientStream,false );
// Pass the NegotiateStream as the AsyncState object
// so that it is available to the callback delegate.
IAsyncResult^ ar = authStream->BeginAuthenticateAsClient( gcnew AsyncCallback( EndAuthenticateCallback ), authStream );
Console::WriteLine( L"Client waiting for authentication..." );
// Wait until the result is available.
ar->AsyncWaitHandle->WaitOne();
// Display the properties of the authenticated stream.
AuthenticatedStreamReporter::DisplayProperties( authStream );
// Send a message to the server.
// Encode the test data into a byte array.
array<Byte>^message = Encoding::UTF8->GetBytes( L"Hello from the client." );
ar = authStream->BeginWrite( message, 0, message->Length, gcnew AsyncCallback( EndWriteCallback ), authStream );
// Request authentication.
NetworkStream clientStream = client.GetStream();
NegotiateStream authStream = new NegotiateStream(clientStream, false);
// Pass the NegotiateStream as the AsyncState object
// so that it is available to the callback delegate.
Task authenticateTask = authStream
.AuthenticateAsClientAsync()
.ContinueWith(task =>
{
Console.WriteLine("Client ending authentication...");
Console.WriteLine("ImpersonationLevel: {0}", authStream.ImpersonationLevel);
});
Console.WriteLine("Client waiting for authentication...");
// Wait until the result is available.
authenticateTask.Wait();
// Display the properties of the authenticated stream.
AuthenticatedStreamReporter.DisplayProperties(authStream);
// Send a message to the server.
// Encode the test data into a byte array.
byte[] message = Encoding.UTF8.GetBytes("Hello from the client.");
Task writeTask = authStream
.WriteAsync(message, 0, message.Length)
.ContinueWith(task =>
{
Console.WriteLine("Client ending write operation...");
});
' Request authentication.
Dim clientStream = client.GetStream()
Dim authStream As New NegotiateStream(clientStream, False)
' Pass the NegotiateStream as the AsyncState object
' so that it is available to the callback delegate.
Dim ar = authStream.BeginAuthenticateAsClient(
New AsyncCallback(AddressOf EndAuthenticateCallback), authStream)
Console.WriteLine("Client waiting for authentication...")
' Wait until the result is available.
ar.AsyncWaitHandle.WaitOne()
' Display the properties of the authenticated stream.
AuthenticatedStreamReporter.DisplayProperties(authStream)
' Send a message to the server.
' Encode the test data into a byte array.
Dim message = Encoding.UTF8.GetBytes("Hello from the client.")
ar = authStream.BeginWrite(message, 0, message.Length,
New AsyncCallback(AddressOf EndWriteCallback), authStream)
O método a seguir é chamado quando a operação é concluída.The following method is called when the operation completes.
// The following method is called when the write operation completes.
static void EndWriteCallback( IAsyncResult^ ar )
{
Console::WriteLine( L"Client ending write operation..." );
NegotiateStream^ authStream = dynamic_cast<NegotiateStream^>(ar->AsyncState);
// End the asynchronous operation.
authStream->EndWrite( ar );
}
' The following method is called when the write operation completes.
Public Shared Sub EndWriteCallback(ar As IAsyncResult)
Console.WriteLine("Client ending write operation...")
Dim authStream = CType(ar.AsyncState, NegotiateStream)
' End the asynchronous operation.
authStream.EndWrite(ar)
End Sub
Comentários
Se a criptografia, assinatura ou criptografia e assinatura estiverem habilitadas, esse método lerá os dados do buffer, criptografará, assinará ou criptografará e o transformará, e o transmitirá usando o fluxo subjacente.If encryption, signing, or encryption and signing are enabled, this method reads the data from buffer, encrypts, signs, or encrypts and signs it, and transmits it using the underlying stream. Se nenhum serviço de segurança, como criptografia de dados ou assinatura, estiver em uso, esse método iniciará uma operação de gravação assíncrona no fluxo subjacente.If no security services such as data encryption or signing are in use, this method starts an asynchronous write operation on the underlying stream.
Esse método é assíncrono e não é bloqueado enquanto a operação é concluída.This method is asynchronous and does not block while the operation completes. Para bloquear até que a operação seja concluída, use o Read método.To block until the operation completes, use the Read method.
A operação de leitura assíncrona deve ser concluída chamando o EndWrite método.The asynchronous read operation must be completed by calling the EndWrite method. Normalmente, o método é invocado pelo asyncCallback delegado.Typically, the method is invoked by the asyncCallback delegate. Para obter informações detalhadas sobre como usar o modelo de programação assíncrona, consulte chamando métodos síncronos de forma assíncronaFor detailed information about using the asynchronous programming model, see Calling Synchronous Methods Asynchronously
A NegotiateStream classe não oferece suporte a várias operações simultâneas de gravação.The NegotiateStream class does not support multiple simultaneous write operations. Se você tentar iniciar uma operação de gravação enquanto outra operação de gravação já estiver em execução no mesmo fluxo, uma NotSupportedException exceção será lançada.If you attempt to start a write operation while another write operation is already executing on the same stream, a NotSupportedException exception will be thrown.
Você não pode chamar esse método até que você tenha autenticado com êxito.You cannot call this method until you have successfully authenticated. Para autenticar, chame um dos AuthenticateAsClient AuthenticateAsClientAsync métodos,, BeginAuthenticateAsClient ,, AuthenticateAsServer AuthenticateAsServerAsync ou BeginAuthenticateAsServer .To authenticate, call one of the AuthenticateAsClient, AuthenticateAsClientAsync, BeginAuthenticateAsClient, AuthenticateAsServer, AuthenticateAsServerAsync, or BeginAuthenticateAsServer methods.