NegotiateStream.BeginWrite Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Inicia uma operação de escrita assíncrona que escreve Bytes do buffer especificado para o fluxo.
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
- offset
- Int32
A localização em base zero onde buffer começar a ler bytes a serem escritos no fluxo.
- asyncCallback
- AsyncCallback
Um AsyncCallback delegado que faz referência ao método a invocar quando a operação de escrita está concluída.
- asyncState
- Object
Um objeto definido pelo utilizador contendo informação sobre a operação de escrita. Este objeto é passado para o asyncCallback delegado quando a operação termina.
Devoluções
Um objeto que IAsyncResult indica o estado da operação assíncrona.
Exceções
buffer é null.
offset é inferior a 0.
-ou-
offset é maior do que o comprimento de buffer.
-ou-
offset mais contagem é maior do que o comprimento de buffer.
A operação de escrita falhou.
-ou-
A encriptação está em uso, mas os dados não puderam ser encriptados.
Já está em curso uma operação de escrita.
Este objeto foi encerrado.
A autenticação não ocorreu.
Exemplos
O exemplo seguinte demonstra o início de uma operação de escrita assíncrona.
// 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 seguinte método é chamado quando a operação termina.
' 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
Observações
Se a encriptação, assinatura ou encriptação e assinatura estiverem ativados, este método lê os dados do buffer, encripta, assina ou encripta-os e assina-os, e transmite-os usando o fluxo subjacente. Se não forem utilizados serviços de segurança como encriptação ou assinatura de dados, este método inicia uma operação de escrita assíncrona no fluxo subjacente.
Este método é assíncrono e não bloqueia enquanto a operação está concluída. Para bloquear até a operação terminar, use o Read método.
A operação de leitura assíncrona deve ser completada chamando o EndWrite método. Normalmente, o método é invocado pelo asyncCallback delegado. Para informações detalhadas sobre a utilização do modelo de programação assíncrona, veja Chamar Métodos Síncronos Assíncronos
A NegotiateStream classe não suporta múltiplas operações de escrita simultâneas. Se tentar iniciar uma operação de escrita enquanto outra já está a ser executada no mesmo fluxo, será lançada uma NotSupportedException exceção.
Não pode chamar este método até ter autenticado com sucesso. Para autenticar, chame um dos AuthenticateAsClient, AuthenticateAsClientAsync, BeginAuthenticateAsClient, AuthenticateAsServer, AuthenticateAsServerAsync, ou BeginAuthenticateAsServer métodos.