NegotiateStream.BeginWrite Método

Definición

Inicia una operación de escritura asincrónica que escribe Bytes desde el búfer especificado en la secuencia.

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[]

Matriz Byte que proporciona los bytes que se van a escribir en la secuencia.

offset
Int32

La ubicación de base cero de buffer en la que se va a empezar a leer los bytes que se van a escribir en la secuencia.

count
Int32

Valor de Int32 que especifica el número de bytes que se van a al leer desde buffer.

asyncCallback
AsyncCallback

Delegado de AsyncCallback que hace referencia al método que se va a invocar una vez finalizada la operación de escritura.

asyncState
Object

Objeto definido por el usuario que contiene información sobre la operación de escritura. Este objeto se pasa al delegado de asyncCallback cuando la operación ha terminado.

Devoluciones

Objeto IAsyncResult que indica el estado de la operación asincrónica.

Excepciones

buffer es null.

offset is less than 0.

o bien

offset es mayor que la longitud de buffer.

o bien

La suma de offset y el recuento es mayor que la longitud de buffer.

No se pudo realizar la operación de escritura.

o bien

El cifrado está en uso, pero no se pudieron cifrar los datos.

Ya hay una operación de escritura en curso.

Este objeto se ha cerrado.

No se ha producido la autenticación.

Ejemplos

En el ejemplo siguiente se muestra cómo iniciar una operación de escritura asincrónica.

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

Se llama al método siguiente cuando se completa la operación.

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

Comentarios

Si el cifrado, la firma o el cifrado y la firma están habilitados, este método lee los datos del búfer, cifra, firma o cifra y lo firma, y lo transmite mediante la secuencia subyacente. Si no se usan servicios de seguridad como el cifrado de datos o la firma, este método inicia una operación de escritura asincrónica en la secuencia subyacente.

Este método es asincrónico y no se bloquea mientras se completa la operación. Para bloquear hasta que se complete la operación, use el Read método .

La operación de lectura asincrónica debe completarse llamando al EndWrite método . Normalmente, el delegado invoca el asyncCallback método . Para obtener información detallada sobre cómo usar el modelo de programación asincrónica, vea Llamar a métodos sincrónicos de forma asincrónica.

La NegotiateStream clase no admite varias operaciones de escritura simultáneas. Si intenta iniciar una operación de escritura mientras otra operación de escritura ya se está ejecutando en la misma secuencia, se producirá una NotSupportedException excepción.

No puede llamar a este método hasta que se haya autenticado correctamente. Para autenticarse, llame a uno de los AuthenticateAsClientmétodos , AuthenticateAsClientAsync, BeginAuthenticateAsClient, AuthenticateAsServer, AuthenticateAsServerAsynco BeginAuthenticateAsServer .

Se aplica a