NegotiateStream.Write(Byte[], Int32, Int32) Método

Definición

Escriba el número especificado de Bytes en la secuencia subyacente mediante el búfer y el desplazamiento especificados.

public:
 override void Write(cli::array <System::Byte> ^ buffer, int offset, int count);
public override void Write (byte[] buffer, int offset, int count);
override this.Write : byte[] * int * int -> unit
Public Overrides Sub Write (buffer As Byte(), offset As Integer, count As Integer)

Parámetros

buffer
Byte[]

Matriz de Byte que proporciona los bytes escritos en la secuencia.

offset
Int32

Int32 que contiene 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

Int32 que contiene el número de bytes que se van a leer de buffer.

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 de código siguiente se muestra cómo escribir en un NegotiateStreamobjeto .

int main()
{
   
   // Establish the remote endpoint for the socket.
   // For this example, use the local machine.
   IPHostEntry^ ipHostInfo = Dns::GetHostEntry( Dns::GetHostName() );
   IPAddress^ ipAddress = ipHostInfo->AddressList[ 0 ];
   
   // Client and server use port 11000. 
   IPEndPoint^ remoteEP = gcnew IPEndPoint( ipAddress,11000 );
   
   // Create a TCP/IP socket.
   TcpClient^ client = gcnew TcpClient;
   
   // Connect the socket to the remote endpoint.
   client->Connect( remoteEP );
   Console::WriteLine( L"Client connected to {0}.", remoteEP );
   
   // Ensure the client does not close when there is 
   // still data to be sent to the server.
   client->LingerState = (gcnew LingerOption( true,0 ));
   
   // Request authentication.
   NetworkStream^ clientStream = client->GetStream();
   NegotiateStream^ authStream = gcnew NegotiateStream( clientStream );
   
   // Request authentication for the client only (no mutual authentication).
   // Authenicate using the client's default credetials.
   // Permit the server to impersonate the client to access resources on the server only.
   // Request that data be transmitted using encryption and data signing.
   authStream->AuthenticateAsClient( dynamic_cast<NetworkCredential^>(CredentialCache::DefaultCredentials), 
          L"", 
          ProtectionLevel::EncryptAndSign, 
          TokenImpersonationLevel::Impersonation );
   
   DisplayAuthenticationProperties( authStream );
   DisplayStreamProperties( authStream );
   if ( authStream->CanWrite )
   {
      
      // Encode the test data into a byte array.
      array<Byte>^message = System::Text::Encoding::UTF8->GetBytes( L"Hello from the client." );
      authStream->Write( message, 0, message->Length );
      authStream->Flush();
      Console::WriteLine( L"Sent {0} bytes.", message->Length );
   }

   
   // Close the client connection.
   authStream->Close();
   Console::WriteLine( L"Client closed." );
}

    public static void Main(String[] args)
    {
        // Establish the remote endpoint for the socket.
        // For this example, use the local machine.
        IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        // Client and server use port 11000.
        IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
        // Create a TCP/IP socket.
       TcpClient client = new TcpClient();
        // Connect the socket to the remote endpoint.
        client.Connect(remoteEP);
        Console.WriteLine("Client connected to {0}.",
            remoteEP.ToString());
        // Ensure the client does not close when there is
        // still data to be sent to the server.
        client.LingerState = (new LingerOption(true,0));
        // Request authentication.
        NetworkStream clientStream = client.GetStream();
        NegotiateStream authStream = new NegotiateStream(clientStream);
        // Request authentication for the client only (no mutual authentication).
        // Authenicate using the client's default credetials.
        // Permit the server to impersonate the client to access resources on the server only.
        // Request that data be transmitted using encryption and data signing.
        authStream.AuthenticateAsClient(
             (NetworkCredential) CredentialCache.DefaultCredentials,
             "",
             ProtectionLevel.EncryptAndSign,
             TokenImpersonationLevel.Impersonation);
        DisplayAuthenticationProperties(authStream);
        DisplayStreamProperties(authStream);
        if (authStream.CanWrite)
        {
             // Encode the test data into a byte array.
            byte[] message = System.Text.Encoding.UTF8.GetBytes("Hello from the client.");
            authStream.Write(message, 0, message.Length);
            authStream.Flush();
            Console.WriteLine("Sent {0} bytes.", message.Length);
        }
        // Close the client connection.
        authStream.Close();
        Console.WriteLine("Client closed.");
}

Comentarios

Si se habilitan el cifrado, la firma o el cifrado y la firma, 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 invoca Write en la secuencia subyacente.

Este método se bloquea mientras se completa la operación de escritura. Para evitar el bloqueo mientras se completa la operación, use el WriteAsync método .

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

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.

Se aplica a