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

Definição

Grave o número especificado de Bytes no fluxo subjacente usando o buffer e o deslocamento 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[]

Uma matriz Byte que fornece os bytes gravados no fluxo.

offset
Int32

Um Int32 contendo a localização baseada em zero no buffer em que será iniciada a leitura dos bytes a serem gravados no fluxo.

count
Int32

Um Int32 contendo o número de bytes a serem lidos do buffer.

Exceções

buffer é null.

offset is less than 0.

- ou - offset é maior que o comprimento do buffer.

- ou - offset mais a contagem é maior que o comprimento de buffer.

A operação de gravação falhou.

- ou -

A criptografia está em uso, mas não foi possível criptografar os dados.

Já existe uma operação de gravação em andamento.

Este objeto foi fechado.

A autenticação não ocorreu.

Exemplos

O exemplo de código a seguir demonstra a gravação em um NegotiateStream.

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.");
}

Comentários

Se a criptografia, a assinatura ou a criptografia e a assinatura estiverem habilitadas, esse método lerá os dados do buffer, criptografará, assinará ou criptografará-os e os transmitirá usando o fluxo subjacente. Se nenhum serviço de segurança, como criptografia de dados ou assinatura, estiver em uso, esse método invocará Write no fluxo subjacente.

Esse método bloqueia enquanto a operação de gravação é concluída. Para evitar o bloqueio durante a conclusão da operação, use o WriteAsync método.

Não é possível chamar esse método até que você tenha se autenticado com êxito. Para autenticar, chame um dos AuthenticateAsClientmétodos ou BeginAuthenticateAsClientAuthenticateAsServerAsyncAuthenticateAsClientAsyncAuthenticateAsServerBeginAuthenticateAsServer métodos.

A NegotiateStream classe não dá suporte a várias operações de gravação simultâneas. 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á gerada.

Aplica-se a