共用方式為


SslStream 類別

定義

提供用於用戶端-伺服器通訊的數據流,該數據流會使用安全套接字層 (SSL) 安全性通訊協定來驗證伺服器,並選擇性地驗證用戶端。

public ref class SslStream : System::Net::Security::AuthenticatedStream
public class SslStream : System.Net.Security.AuthenticatedStream
type SslStream = class
    inherit AuthenticatedStream
Public Class SslStream
Inherits AuthenticatedStream
繼承
繼承

範例

下列程式代碼範例示範如何建立使用 SslStream 類別來與用戶端通訊的 TcpListener

#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Net::Security;
using namespace System::Security::Authentication;
using namespace System::Text;
using namespace System::Security::Cryptography::X509Certificates;
using namespace System::IO;
public ref class SslTcpServer sealed
{
private:
   static X509Certificate^ serverCertificate = nullptr;

public:

   // The certificate parameter specifies the name of the file 
   // containing the machine certificate.
   static void RunServer( String^ certificate )
   {
      serverCertificate = X509Certificate::CreateFromCertFile( certificate );
      
      // Create a TCP/IP (IPv4) socket and listen for incoming connections.
      TcpListener^ listener = gcnew TcpListener( IPAddress::Any,5000 );
      listener->Start();
      
      while (true) 
      {
         Console::WriteLine( L"Waiting for a client to connect..." );
         
         // Application blocks while waiting for an incoming connection.
         // Type CNTL-C to terminate the server.
         TcpClient^ client = listener->AcceptTcpClient();
         ProcessClient( client );

      }
   }


   static void ProcessClient( TcpClient^ client )
   {
      
      // A client has connected. Create the 
      // SslStream using the client's network stream.
      SslStream^ sslStream = gcnew SslStream( client->GetStream(),false );
      
      // Authenticate the server but don't require the client to authenticate.
      try
      {
         sslStream->AuthenticateAsServer( serverCertificate, false, true );
         // false == no client cert required; true == check cert revocation.
         
         // Display the properties and settings for the authenticated stream.
         DisplaySecurityLevel( sslStream );
         DisplaySecurityServices( sslStream );
         DisplayCertificateInformation( sslStream );
         DisplayStreamProperties( sslStream );
         
         // Set timeouts for the read and write to 5 seconds.
         sslStream->ReadTimeout = 5000;
         sslStream->WriteTimeout = 5000;
         
         // Read a message from the client.   
         Console::WriteLine( L"Waiting for client message..." );
         String^ messageData = ReadMessage( sslStream );
         Console::WriteLine( L"Received: {0}", messageData );
         
         // Write a message to the client.
         array<Byte>^message = Encoding::UTF8->GetBytes( L"Hello from the server.<EOF>" );
         Console::WriteLine( L"Sending hello message." );
         sslStream->Write( message );
      }
      catch ( AuthenticationException^ e ) 
      {
         Console::WriteLine( L"Exception: {0}", e->Message );
         if ( e->InnerException != nullptr )
         {
            Console::WriteLine( L"Inner exception: {0}", e->InnerException->Message );
         }
         Console::WriteLine( L"Authentication failed - closing the connection." );
         sslStream->Close();
         client->Close();
         return;
      }
      finally
      {
         
         // The client stream will be closed with the sslStream
         // because we specified this behavior when creating
         // the sslStream.
         sslStream->Close();
         client->Close();
      }

   }


   static String^ ReadMessage( SslStream^ sslStream )
   {
      
      // Read the  message sent by the client.
      // The client signals the end of the message using the
      // "<EOF>" marker.
      array<Byte>^buffer = gcnew array<Byte>(2048);
      StringBuilder^ messageData = gcnew StringBuilder;
      int bytes = -1;
      do
      {
         
         // Read the client's test message.
         bytes = sslStream->Read( buffer, 0, buffer->Length );
         
         // Use Decoder class to convert from bytes to UTF8
         // in case a character spans two buffers.
         Decoder^ decoder = Encoding::UTF8->GetDecoder();
         array<Char>^chars = gcnew array<Char>(decoder->GetCharCount( buffer, 0, bytes ));
         decoder->GetChars( buffer, 0, bytes, chars, 0 );
         messageData->Append( chars );
         
         // Check for EOF or an empty message.
         if ( messageData->ToString()->IndexOf( L"<EOF>" ) != -1 )
         {
            break;
         }
      }
      while ( bytes != 0 );

      return messageData->ToString();
   }


   static void DisplaySecurityLevel( SslStream^ stream )
   {
      Console::WriteLine( L"Cipher: {0} strength {1}", stream->CipherAlgorithm, stream->CipherStrength );
      Console::WriteLine( L"Hash: {0} strength {1}", stream->HashAlgorithm, stream->HashStrength );
      Console::WriteLine( L"Key exchange: {0} strength {1}", stream->KeyExchangeAlgorithm, stream->KeyExchangeStrength );
      Console::WriteLine( L"Protocol: {0}", stream->SslProtocol );
   }


   static void DisplaySecurityServices( SslStream^ stream )
   {
      Console::WriteLine( L"Is authenticated: {0} as server? {1}", stream->IsAuthenticated, stream->IsServer );
      Console::WriteLine( L"IsSigned: {0}", stream->IsSigned );
      Console::WriteLine( L"Is Encrypted: {0}", stream->IsEncrypted );
      Console::WriteLine( L"Is mutually authenticated: {0}", stream->IsMutuallyAuthenticated );
   }


   static void DisplayStreamProperties( SslStream^ stream )
   {
      Console::WriteLine( L"Can read: {0}, write {1}", stream->CanRead, stream->CanWrite );
      Console::WriteLine( L"Can timeout: {0}", stream->CanTimeout );
   }


   static void DisplayCertificateInformation( SslStream^ stream )
   {
      Console::WriteLine( L"Certificate revocation list checked: {0}", stream->CheckCertRevocationStatus );
      X509Certificate^ localCertificate = stream->LocalCertificate;
      if ( stream->LocalCertificate != nullptr )
      {
         Console::WriteLine( L"Local cert was issued to {0} and is valid from {1} until {2}.", 
             localCertificate->Subject, 
             localCertificate->GetEffectiveDateString(), 
             localCertificate->GetExpirationDateString() );
      }
      else
      {
         Console::WriteLine( L"Local certificate is null." );
      }

      X509Certificate^ remoteCertificate = stream->RemoteCertificate;
      if ( stream->RemoteCertificate != nullptr )
      {
         Console::WriteLine( L"Remote cert was issued to {0} and is valid from {1} until {2}.", 
            remoteCertificate->Subject, 
            remoteCertificate->GetEffectiveDateString(), 
            remoteCertificate->GetExpirationDateString() );
      }
      else
      {
         Console::WriteLine( L"Remote certificate is null." );
      }
   }


private:

   static void DisplayUsage()
   {
      Console::WriteLine( L"To start the server specify:" );
      Console::WriteLine( L"serverSync certificateFile.cer" );
      Environment::Exit( 1 );
   }

public:
   int RunServerASync()
   {
      array<String^>^args = Environment::GetCommandLineArgs();
      String^ certificate = nullptr;
      if ( args == nullptr || args->Length < 2 )
      {
         DisplayUsage();
      }

      certificate = args[ 1 ];
      SslTcpServer::RunServer( certificate );
      return 0;
   }

};

int main(){
    SslTcpServer^ sts = gcnew SslTcpServer();
    sts->RunServerASync();
}
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace Examples.System.Net
{
    public sealed class SslTcpServer
    {
        static X509Certificate serverCertificate = null;
        // The certificate parameter specifies the name of the file
        // containing the machine certificate.
        public static void RunServer(string certificate)
        {
            serverCertificate = X509Certificate.CreateFromCertFile(certificate);
            // Create a TCP/IP (IPv4) socket and listen for incoming connections.
            TcpListener listener = new TcpListener(IPAddress.Any, 5000);
            listener.Start();
            while (true)
            {
                Console.WriteLine("Waiting for a client to connect...");
                // Application blocks while waiting for an incoming connection.
                // Type CNTL-C to terminate the server.
                TcpClient client = listener.AcceptTcpClient();
                ProcessClient(client);
            }
        }
        static void ProcessClient (TcpClient client)
        {
            // A client has connected. Create the
            // SslStream using the client's network stream.
            SslStream sslStream = new SslStream(
                client.GetStream(), false);
            // Authenticate the server but don't require the client to authenticate.
            try
            {
                sslStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired: false, checkCertificateRevocation: true);

                // Display the properties and settings for the authenticated stream.
                DisplaySecurityLevel(sslStream);
                DisplaySecurityServices(sslStream);
                DisplayCertificateInformation(sslStream);
                DisplayStreamProperties(sslStream);

                // Set timeouts for the read and write to 5 seconds.
                sslStream.ReadTimeout = 5000;
                sslStream.WriteTimeout = 5000;
                // Read a message from the client.
                Console.WriteLine("Waiting for client message...");
                string messageData = ReadMessage(sslStream);
                Console.WriteLine("Received: {0}", messageData);

                // Write a message to the client.
                byte[] message = Encoding.UTF8.GetBytes("Hello from the server.<EOF>");
                Console.WriteLine("Sending hello message.");
                sslStream.Write(message);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine ("Authentication failed - closing the connection.");
                sslStream.Close();
                client.Close();
                return;
            }
            finally
            {
                // The client stream will be closed with the sslStream
                // because we specified this behavior when creating
                // the sslStream.
                sslStream.Close();
                client.Close();
            }
        }
        static string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the client.
            // The client signals the end of the message using the
            // "<EOF>" marker.
            byte [] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                // Read the client's test message.
                bytes = sslStream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
                decoder.GetChars(buffer, 0, bytes, chars,0);
                messageData.Append (chars);
                // Check for EOF or an empty message.
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes !=0);

            return messageData.ToString();
        }
         static void DisplaySecurityLevel(SslStream stream)
         {
            Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
            Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
            Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
            Console.WriteLine("Protocol: {0}", stream.SslProtocol);
         }
         static void DisplaySecurityServices(SslStream stream)
         {
            Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer);
            Console.WriteLine("IsSigned: {0}", stream.IsSigned);
            Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted);
            Console.WriteLine("Is mutually authenticated: {0}", stream.IsMutuallyAuthenticated);
         }
         static void DisplayStreamProperties(SslStream stream)
         {
            Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite);
            Console.WriteLine("Can timeout: {0}", stream.CanTimeout);
         }
        static void DisplayCertificateInformation(SslStream stream)
        {
            Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus);

            X509Certificate localCertificate = stream.LocalCertificate;
            if (stream.LocalCertificate != null)
            {
                Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.",
                    localCertificate.Subject,
                    localCertificate.GetEffectiveDateString(),
                    localCertificate.GetExpirationDateString());
             } else
            {
                Console.WriteLine("Local certificate is null.");
            }
            // Display the properties of the client's certificate.
            X509Certificate remoteCertificate = stream.RemoteCertificate;
            if (stream.RemoteCertificate != null)
            {
            Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.",
                remoteCertificate.Subject,
                remoteCertificate.GetEffectiveDateString(),
                remoteCertificate.GetExpirationDateString());
            } else
            {
                Console.WriteLine("Remote certificate is null.");
            }
        }
        private static void DisplayUsage()
        {
            Console.WriteLine("To start the server specify:");
            Console.WriteLine("serverSync certificateFile.cer");
            Environment.Exit(1);
        }
        public static int Main(string[] args)
        {
            string certificate = null;
            if (args == null ||args.Length < 1 )
            {
                DisplayUsage();
            }
            certificate = args[0];
            SslTcpServer.RunServer (certificate);
            return 0;
        }
    }
}
Imports System.Collections
Imports System.Net
Imports System.Net.Sockets
Imports System.Net.Security
Imports System.Security.Authentication
Imports System.Text
Imports System.Security.Cryptography.X509Certificates
Imports System.IO

Namespace Examples.System.Net
    Public NotInheritable Class SslTcpServer
        Shared serverCertificate As X509Certificate = Nothing

        ' The certificate parameter specifies the name of the file 
        ' containing the machine certificate.
        Public Shared Sub RunServer(certificate As String)
            serverCertificate = X509Certificate.CreateFromCertFile(certificate)
            ' Create a TCP/IP (IPv4) socket And listen for incoming connections.
            Dim listener = New TcpListener(IPAddress.Any, 5000)
            listener.Start()

            While True
                Console.WriteLine("Waiting for a client to connect...")
                ' Application blocks while waiting for an incoming connection.
                ' Type CNTL-C to terminate the server.
                Dim client As TcpClient = listener.AcceptTcpClient()
                ProcessClient(client)
            End While
        End Sub
        Private Shared Sub ProcessClient(client As TcpClient)
            ' A client has connected. Create the 
            ' SslStream using the client's network stream.
            Dim sslStream = New SslStream(client.GetStream(), False)

            Try

                sslStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired:=False, checkCertificateRevocation:=True)
                ' Display the properties And settings for the authenticated stream.
                DisplaySecurityLevel(sslStream)
                DisplaySecurityServices(sslStream)
                DisplayCertificateInformation(sslStream)
                DisplayStreamProperties(sslStream)

                ' Set timeouts for the read and write to 5 seconds.
                sslStream.ReadTimeout = 5000
                sslStream.WriteTimeout = 5000

                ' Read a message from the client.   
                Console.WriteLine("Waiting for client message...")
                Dim messageData As String = ReadMessage(sslStream)
                Console.WriteLine("Received: {0}", messageData)

                ' Write a message to the client.
                Dim message As Byte() = Encoding.UTF8.GetBytes("Hello from the server.<EOF>")
                Console.WriteLine("Sending hello message.")
                sslStream.Write(message)
            Catch e As AuthenticationException
                Console.WriteLine("Exception: {0}", e.Message)

                If e.InnerException IsNot Nothing Then
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message)
                End If

                Console.WriteLine("Authentication failed - closing the connection.")
                sslStream.Close()
                client.Close()
                Return
            Finally
                ' The client stream will be closed with the sslStream
                ' because we specified this behavior when creating
                ' the sslStream.
                sslStream.Close()
                client.Close()
            End Try
        End Sub

        Private Shared Function ReadMessage(sslStream As SslStream) As String

            ' Read the  message sent by the client.
            ' The client signals the end of the message using the
            ' "<EOF>" marker.
            Dim buffer As Byte() = New Byte(2048) {}
            Dim messageData As StringBuilder = New StringBuilder()
            Dim bytes As Integer = -1

            Do
                ' Read the client's test message.
                bytes = sslStream.Read(buffer, 0, buffer.Length)

                ' Use decoder class to convert from bytes to UTF8
                ' in case a character spans two buffers.
                Dim decoder As Decoder = Encoding.UTF8.GetDecoder()
                Dim chars As Char() = New Char(decoder.GetCharCount(buffer, 0, bytes) - 1) {}
                decoder.GetChars(buffer, 0, bytes, chars, 0)
                messageData.Append(chars)

                ' Check for EOF or an empty message.
                If messageData.ToString().IndexOf("<EOF>") <> -1 Then
                    Exit Do
                End If
            Loop While bytes <> 0

            Return messageData.ToString()
        End Function

        Private Shared Sub DisplaySecurityLevel(stream As SslStream)
            Console.WriteLine("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength)
            Console.WriteLine("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength)
            Console.WriteLine("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength)
            Console.WriteLine("Protocol: {0}", stream.SslProtocol)
        End Sub

        Private Shared Sub DisplaySecurityServices(stream As SslStream)
            Console.WriteLine("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer)
            Console.WriteLine("IsSigned: {0}", stream.IsSigned)
            Console.WriteLine("Is Encrypted: {0}", stream.IsEncrypted)
            Console.WriteLine("Is mutually authenticated: {0}", stream.IsMutuallyAuthenticated)
        End Sub

        Private Shared Sub DisplayStreamProperties(stream As SslStream)
            Console.WriteLine("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite)
            Console.WriteLine("Can timeout: {0}", stream.CanTimeout)
        End Sub

        Private Shared Sub DisplayCertificateInformation(stream As SslStream)
            Console.WriteLine("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus)
            Dim localCertificate As X509Certificate = stream.LocalCertificate

            If stream.LocalCertificate IsNot Nothing Then
                Console.WriteLine("Local cert was issued to {0} and is valid from {1} until {2}.", localCertificate.Subject, localCertificate.GetEffectiveDateString(), localCertificate.GetExpirationDateString())
            Else
                Console.WriteLine("Local certificate is null.")
            End If

            ' Display the properties of the client's certificate.
            Dim remoteCertificate As X509Certificate = stream.RemoteCertificate

            If stream.RemoteCertificate IsNot Nothing Then
                Console.WriteLine("Remote cert was issued to {0} and is valid from {1} until {2}.", remoteCertificate.Subject, remoteCertificate.GetEffectiveDateString(), remoteCertificate.GetExpirationDateString())
            Else
                Console.WriteLine("Remote certificate is null.")
            End If
        End Sub

        Private Shared Sub DisplayUsage()
            Console.WriteLine("To start the server specify:")
            Console.WriteLine("serverSync certificateFile.cer")
            Environment.[Exit](1)
        End Sub

        Public Shared Function Main(ByVal args As String()) As Integer
            Dim certificate As String

            If args Is Nothing OrElse args.Length < 1 Then
                DisplayUsage()
            End If

            certificate = args(0)
            RunServer(certificate)
            Return 0
        End Function
    End Class
End Namespace

下列程式代碼範例示範如何建立使用 SslStream 類別與伺服器通訊的 TcpClient

#using <System.dll>
#using <System.Security.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;
using namespace System::Net;
using namespace System::Net::Security;
using namespace System::Net::Sockets;
using namespace System::Security::Authentication;
using namespace System::Text;
using namespace System::Security::Cryptography::X509Certificates;
using namespace System::IO;

namespace NlsClientSync
{
    public ref class SslTcpClient
    {
    private:
        static Hashtable^ certificateErrors = gcnew Hashtable;
        // Load a table of errors that might cause 
        // the certificate authentication to fail.
        static void InitializeCertificateErrors()
        {
            certificateErrors->Add(0x800B0101,
                "The certification has expired.");
            certificateErrors->Add(0x800B0104,
                "A path length constraint "
                "in the certification chain has been violated.");
            certificateErrors->Add(0x800B0105,
                "A certificate contains an unknown extension "
                "that is marked critical.");
            certificateErrors->Add(0x800B0107,
                "A parent of a given certificate in fact "
                "did not issue that child certificate.");
            certificateErrors->Add(0x800B0108,
                "A certificate is missing or has an empty value "
                "for a necessary field.");
            certificateErrors->Add(0x800B0109,
                "The certificate root is not trusted.");
            certificateErrors->Add(0x800B010C,
                "The certificate has been revoked.");
            certificateErrors->Add(0x800B010F,
                "The name in the certificate does not not match "
                "the host name requested by the client.");
            certificateErrors->Add(0x800B0111,
                "The certificate was explicitly marked "
                "as untrusted by the user.");
            certificateErrors->Add(0x800B0112,
                "A certification chain processed correctly, "
                "but one of the CA certificates is not trusted.");
            certificateErrors->Add(0x800B0113,
                "The certificate has an invalid policy.");
            certificateErrors->Add(0x800B0114,
                "The certificate name is either not "
                "in the permitted list or is explicitly excluded.");
            certificateErrors->Add(0x80092012,
                "The revocation function was unable to check "
                "revocation for the certificate.");
            certificateErrors->Add(0x80090327,
                "An unknown error occurred while "
                "processing the certificate.");
            certificateErrors->Add(0x80096001,
                "A system-level error occurred "
                "while verifying trust.");
            certificateErrors->Add(0x80096002,
                "The certificate for the signer of the message "
                "is invalid or not found.");
            certificateErrors->Add(0x80096003,
                "One of the counter signatures was invalid.");
            certificateErrors->Add(0x80096004,
                "The signature of the certificate "
                "cannot be verified.");
            certificateErrors->Add(0x80096005,
                "The time stamp signature or certificate "
                "could not be verified or is malformed.");
            certificateErrors->Add(0x80096010,
                "The digital signature of the object "
                "was not verified.");
            certificateErrors->Add(0x80096019,
                "The basic constraint extension of a certificate "
                "has not been observed.");
        }

        static String^ CertificateErrorDescription(UInt32 problem)
        {
            // Initialize the error message dictionary 
            // if it is not yet available.
            if (certificateErrors->Count == 0)
            {
                InitializeCertificateErrors();
            }

            String^ description = safe_cast<String^>(
                certificateErrors[problem]);
            if (description == nullptr)
            {
                description = String::Format(
                    CultureInfo::CurrentCulture,
                    "Unknown certificate error - 0x{0:x8}",
                    problem);
            }

            return description;
        }

    public:
        // The following method is invoked 
        // by the CertificateValidationDelegate.
    static bool ValidateServerCertificate(
            Object^ sender,
            X509Certificate^ certificate,
            X509Chain^ chain,
            SslPolicyErrors sslPolicyErrors)
        {
        
            Console::WriteLine("Validating the server certificate.");
            if (sslPolicyErrors == SslPolicyErrors::None)
                return true;

            Console::WriteLine("Certificate error: {0}", sslPolicyErrors);

            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }

        static void RunClient(String^ machineName, String^ serverName)
        {
              
            // Create a TCP/IP client socket.
            // machineName is the host running the server application.
            TcpClient^ client = gcnew TcpClient(machineName, 5000);
            Console::WriteLine("Client connected.");
              
            // Create an SSL stream that will close 
            // the client's stream.
            SslStream^ sslStream = gcnew SslStream(
                client->GetStream(), false,
                gcnew RemoteCertificateValidationCallback(ValidateServerCertificate),
                nullptr);
              
            // The server name must match the name
            // on the server certificate.
            try
            {
                sslStream->AuthenticateAsClient(serverName);
            }
            catch (AuthenticationException^ ex) 
            {
                Console::WriteLine("Exception: {0}", ex->Message);
                if (ex->InnerException != nullptr)
                {
                    Console::WriteLine("Inner exception: {0}", 
                        ex->InnerException->Message);
                }

                Console::WriteLine("Authentication failed - "
                    "closing the connection.");
                sslStream->Close();
                client->Close();
                return;
            }
            // Encode a test message into a byte array.
            // Signal the end of the message using the "<EOF>".
            array<Byte>^ messsage = Encoding::UTF8->GetBytes(
                "Hello from the client.<EOF>");
              
            // Send hello message to the server.
            sslStream->Write(messsage);
            sslStream->Flush();
            // Read message from the server.
            String^ serverMessage = ReadMessage(sslStream);
            Console::WriteLine("Server says: {0}", serverMessage);
           
            // Close the client connection.
            sslStream->Close();
            client->Close();
            Console::WriteLine("Client closed.");
        }
    private:
        static String^ ReadMessage(SslStream^ sslStream)
        {
              
            // Read the  message sent by the server.
            // The end of the message is signaled using the
            // "<EOF>" marker.
            array<Byte>^ buffer = gcnew array<Byte>(2048);
            StringBuilder^ messageData = gcnew StringBuilder;
            // Use Decoder class to convert from bytes to UTF8
            // in case a character spans two buffers.
            Encoding^ u8 = Encoding::UTF8;
            Decoder^ decoder = u8->GetDecoder();

            int bytes = -1;
            do
            {
                bytes = sslStream->Read(buffer, 0, buffer->Length);
                 
                array<__wchar_t>^ chars = gcnew array<__wchar_t>(
                    decoder->GetCharCount(buffer, 0, bytes));
                decoder->GetChars(buffer, 0, bytes, chars, 0);
                messageData->Append(chars);
                 
                // Check for EOF.
                if (messageData->ToString()->IndexOf("<EOF>") != -1)
                {
                    break;
                }
            }
            while (bytes != 0);

            return messageData->ToString();
        }
    };
}

int main()
{
    array<String^>^ args = Environment::GetCommandLineArgs();
    String^ serverCertificateName = nullptr;
    String^ machineName = nullptr;
    if (args == nullptr || args->Length < 2)
    {
        Console::WriteLine("To start the client specify:");
        Console::WriteLine("clientSync machineName [serverName]");
        return 1;
    }
        
    // User can specify the machine name and server name.
    // Server name must match the name on 
    // the server's certificate.
    machineName = args[1];
    if (args->Length < 3)
    {
        serverCertificateName = machineName;
    }
    else
    {
        serverCertificateName = args[2];
    };

    NlsClientSync::SslTcpClient::RunClient(machineName,
        serverCertificateName);

    return 0;
}
using System;
using System.Collections;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.IO;

namespace Examples.System.Net
{
    public class SslTcpClient
    {
        private static Hashtable certificateErrors = new Hashtable();

        // The following method is invoked by the RemoteCertificateValidationDelegate.
        public static bool ValidateServerCertificate(
              object sender,
              X509Certificate certificate,
              X509Chain chain,
              SslPolicyErrors sslPolicyErrors)
        {
           if (sslPolicyErrors == SslPolicyErrors.None)
                return true;

            Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

            // Do not allow this client to communicate with unauthenticated servers.
            return false;
        }
        public static void RunClient(string machineName, string serverName)
        {
            // Create a TCP/IP client socket.
            // machineName is the host running the server application.
            TcpClient client = new TcpClient(machineName,5000);
            Console.WriteLine("Client connected.");
            // Create an SSL stream that will close the client's stream.
            SslStream sslStream = new SslStream(
                client.GetStream(),
                false,
                new RemoteCertificateValidationCallback (ValidateServerCertificate),
                null
                );
            // The server name must match the name on the server certificate.
            try
            {
                sslStream.AuthenticateAsClient(serverName);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine ("Authentication failed - closing the connection.");
                client.Close();
                return;
            }
            // Encode a test message into a byte array.
            // Signal the end of the message using the "<EOF>".
            byte[] messsage = Encoding.UTF8.GetBytes("Hello from the client.<EOF>");
            // Send hello message to the server.
            sslStream.Write(messsage);
            sslStream.Flush();
            // Read message from the server.
            string serverMessage = ReadMessage(sslStream);
            Console.WriteLine("Server says: {0}", serverMessage);
            // Close the client connection.
            client.Close();
            Console.WriteLine("Client closed.");
        }
        static string ReadMessage(SslStream sslStream)
        {
            // Read the  message sent by the server.
            // The end of the message is signaled using the
            // "<EOF>" marker.
            byte [] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);

                // Use Decoder class to convert from bytes to UTF8
                // in case a character spans two buffers.
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
                decoder.GetChars(buffer, 0, bytes, chars,0);
                messageData.Append (chars);
                // Check for EOF.
                if (messageData.ToString().IndexOf("<EOF>") != -1)
                {
                    break;
                }
            } while (bytes != 0);

            return messageData.ToString();
        }
        private static void DisplayUsage()
        {
            Console.WriteLine("To start the client specify:");
            Console.WriteLine("clientSync machineName [serverName]");
            Environment.Exit(1);
        }
        public static int Main(string[] args)
        {
            string serverCertificateName = null;
            string machineName = null;
            if (args == null ||args.Length <1 )
            {
                DisplayUsage();
            }
            // User can specify the machine name and server name.
            // Server name must match the name on the server's certificate.
            machineName = args[0];
            if (args.Length <2 )
            {
                serverCertificateName = machineName;
            }
            else
            {
                serverCertificateName = args[1];
            }
            SslTcpClient.RunClient (machineName, serverCertificateName);
            return 0;
        }
    }
}
Imports System.Collections
Imports System.Net
Imports System.Net.Security
Imports System.Net.Sockets
Imports System.Security.Authentication
Imports System.Text
Imports System.Security.Cryptography.X509Certificates
Imports System.IO

Namespace Examples.System.Net

    Public Class SslTcpClient
        
        ' The following method is invoked by the RemoteCertificateValidationDelegate.
        Public Shared Function ValidateServerCertificate(
            sender As Object, 
            certificate As X509Certificate, 
            chain As X509Chain, 
            sslPolicyErrors As SslPolicyErrors) As Boolean
            
            If sslPolicyErrors = SslPolicyErrors.None Then Return True

            Console.WriteLine("Certificate error: {0}", sslPolicyErrors)

            ' Do not allow this client to communicate with unauthenticated servers.
            Return False
        End Function
        Public Shared Sub RunClient(machineName As String, serverName As String)

            ' Create a TCP/IP client socket.
            ' machineName is the host running the server application.
            Dim client = New TcpClient(machineName, 5000)
            Console.WriteLine("Client connected.")

            ' Create an SSL stream that will close the client's stream.
            Dim sslStream = New SslStream(
                client.GetStream(), False, 
                New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate), Nothing)

            ' The server name must match the name on the server certificate.
            Try
                sslStream.AuthenticateAsClient(serverName)
            Catch e As AuthenticationException
                Console.WriteLine("Exception: {0}", e.Message)

                If e.InnerException IsNot Nothing Then
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message)
                End If

                Console.WriteLine("Authentication failed - closing the connection.")
                client.Close()
                Return
            End Try
            
            ' Encode a test message into a byte array.
            ' Signal the end of the message using the "<EOF>".
            Dim messsage As Byte() = Encoding.UTF8.GetBytes("Hello from the client.<EOF>")
            
            ' Send hello message to the server.
            sslStream.Write(messsage)
            sslStream.Flush()
            ' Read message from the server.
            Dim serverMessage = ReadMessage(sslStream)
            Console.WriteLine("Server says: {0}", serverMessage)

            ' Close the client connection
            client.Close()
            Console.WriteLine("Client closed.")
        End Sub
        
        Private Shared Function ReadMessage(sslStream As SslStream) As String

            ' Read the  message sent by the server.
            ' The end of the message is signaled using the "<EOF>" marker.
            Dim buffer = New Byte(2048) {}
            Dim messageData = New StringBuilder()
            Dim bytes As Integer

            Do
                bytes = sslStream.Read(buffer, 0, buffer.Length)

                ' Use Decoder class to convert from bytes to UTF8
                ' in case a character spans two buffers.        
                Dim decoder As Decoder = Encoding.UTF8.GetDecoder()
                Dim chars = New Char(decoder.GetCharCount(buffer, 0, bytes) - 1) {}
                decoder.GetChars(buffer, 0, bytes, chars, 0)
                messageData.Append(chars)

                ' Check for EOF.
                If messageData.ToString().IndexOf("<EOF>") <> -1 Then Exit Do
                
            Loop While bytes <> 0

            Return messageData.ToString()

        End Function

        Private Shared Sub DisplayUsage()

            Console.WriteLine("To start the client specify:")
            Console.WriteLine("clientSync machineName [serverName]")
            Environment.[Exit](1)

        End Sub

        Public Shared Function Main(args As String()) As Integer

            Dim serverCertificateName As String
            Dim machineName As String

            If args Is Nothing OrElse args.Length < 1 Then
                DisplayUsage()
            End If

            ' User can specify the machine name and server name.
            ' Server name must match the name on the server's certificate. 
            machineName = args(0)

            If args.Length < 2 Then
                serverCertificateName = machineName
            Else
                serverCertificateName = args(1)
            End If

            SslTcpClient.RunClient(machineName, serverCertificateName)

            Return 0

        End Function

    End Class

End Namespace

備註

SSL 通訊協議有助於提供使用 SslStream傳輸之訊息的機密性和完整性檢查。 在用戶端與伺服器之間通訊敏感性資訊時,應該使用 SSL 連線,例如 SslStream所提供的 SSL 連線。 使用 SslStream 有助於防止任何人在網路上傳輸時讀取和竄改資訊。

SslStream 實例會使用您在建立 SslStream時提供的數據流來傳輸數據。 當您提供此基礎數據流時,可以選擇指定是否關閉 SslStream 也會關閉基礎數據流。 一般而言,SslStream 類別會與 TcpClientTcpListener 類別搭配使用。 GetStream 方法提供適合與 SslStream 類別搭配使用的 NetworkStream

建立 SslStream之後,伺服器和選擇性地必須驗證用戶端。 伺服器必須提供 X509 憑證,以建立其身分識別的證明,並可要求用戶端也這樣做。 必須先執行驗證,才能使用 SslStream傳輸資訊。 用戶端會使用同步 AuthenticateAsClient 方法來起始驗證,此方法會封鎖直到驗證完成為止,或異步 BeginAuthenticateAsClient 方法,而不會封鎖等候驗證完成。 伺服器會使用同步 AuthenticateAsServer 或異步 BeginAuthenticateAsServer 方法來起始驗證。 用戶端和伺服器都必須起始驗證。

驗證是由安全性支援提供者 (SSPI) 通道提供者處理。 用戶端有機會在建立 SslStream時指定 RemoteCertificateValidationCallback 委派,以控制伺服器的憑證驗證。 伺服器也可以藉由提供 RemoteCertificateValidationCallback 委派來控制驗證。 委派所參考的方法包含遠端合作對象的憑證,以及驗證憑證時遇到的任何 SSPI 錯誤。 請注意,如果伺服器指定委派,不論伺服器是否要求客戶端驗證,都會叫用委派的方法。 如果伺服器未要求客戶端驗證,伺服器的委派方法會收到 Null 憑證和空的憑證錯誤數位。

如果伺服器需要客戶端驗證,客戶端必須指定一或多個憑證進行驗證。 如果用戶端有多個憑證,用戶端可以提供 LocalCertificateSelectionCallback 委派,以選取伺服器的正確憑證。 用戶端的憑證必須位於目前使用者的「我的」證書存儲中。 Ssl2 (SSL 第 2 版) 通訊協定不支援透過憑證進行客戶端驗證。

如果驗證失敗,您會收到 AuthenticationException,且 SslStream 已無法使用。 您應該關閉這個物件,並移除它的所有參考,讓垃圾收集行程可以收集它。

當驗證程式也稱為 SSL 交握時,會成功建立伺服器身分識別(以及選擇性地建立用戶端),而且客戶端和伺服器可以使用 SslStream 來交換訊息。 傳送或接收資訊之前,客戶端和伺服器應該檢查 SslStream 所提供的安全性服務和層級,以判斷選取的通訊協定、演算法和強度是否符合其完整性和機密性需求。 如果目前的設定不足,應該關閉數據流。 您可以使用 IsEncryptedIsSigned 屬性來檢查 SslStream 所提供的安全性服務。 下表顯示報告用於驗證、加密和數據簽署之密碼編譯設定的專案。

元素 成員
用來驗證伺服器的安全性通訊協定,以及選擇性地驗證用戶端。 SslProtocol 屬性和相關聯的 SslProtocols 列舉。
金鑰交換演算法。 KeyExchangeAlgorithm 屬性和相關聯的 ExchangeAlgorithmType 列舉。
訊息完整性演算法。 HashAlgorithm 屬性和相關聯的 HashAlgorithmType 列舉。
訊息機密性演算法。 CipherAlgorithm 屬性和相關聯的 CipherAlgorithmType 列舉。
所選演算法的優點。 KeyExchangeStrengthHashStrengthCipherStrength 屬性。

成功驗證之後,您可以使用同步 Write 或異步 BeginWrite 方法來傳送數據。 您可以使用同步 Read 或異步 BeginRead 方法來接收數據。

如果您指定給 SslStream 基礎資料流應該保持開啟狀態,您必須負責在完成使用該數據流時關閉該資料流。

注意

如果建立 SslStream 物件的應用程式會以 Normal 使用者的認證執行,除非已明確將許可權授與使用者,否則應用程式將無法存取本機電腦存放區中安裝的憑證。

SslStream 假設當從內部數據流擲回時,逾時與其他任何 IOException 都會由其呼叫端視為嚴重。 逾時之後重複使用 SslStream 實例會傳回垃圾。 應用程式應該 CloseSslStream,並在這些情況下擲回例外狀況。

.NET Framework 4.6 包含新的安全性功能,可封鎖連線不安全的加密和哈希演算法。 透過 HTTPClient、HttpWebRequest、FTPClient、SmtpClient、SslStream 等 API 使用 TLS/SSL 的應用程式,以及以 .NET Framework 4.6 為目標的應用程式預設會取得更安全的行為。

開發人員可能會想要退出退出此行為,以維持與其現有 SSL3 服務或 TLS w/ RC4 服務的互操作性。 本文 說明如何修改程序代碼,以便停用新的行為。

.NET Framework 4.7 會為驗證未指定 TLS 版本的 SslStreams 的方法新增多載,但改用定義為 SCHANNEL 中系統預設值的 TLS 版本。 在應用程式中使用這些方法作為稍後能夠修改預設值的方式,因為 TLS 版本最佳做法會隨著時間而變更,而不需要重建和重新部署您的應用程式。

另請參閱使用 .NET Framework傳輸層安全性 (TLS) 最佳做法。

建構函式

SslStream(Stream)

使用指定的 Stream,初始化 SslStream 類別的新實例。

SslStream(Stream, Boolean)

使用指定的 Stream 和數據流關閉行為,初始化 SslStream 類別的新實例。

SslStream(Stream, Boolean, RemoteCertificateValidationCallback)

使用指定的 Stream、數據流關閉行為和憑證驗證委派,初始化 SslStream 類別的新實例。

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

使用指定的 Stream、數據流關閉行為、憑證驗證委派和憑證選取委派,初始化 SslStream 類別的新實例。

SslStream(Stream, Boolean, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback, EncryptionPolicy)

使用指定的 Stream,初始化 SslStream 類別的新實例。

屬性

CanRead

取得 Boolean 值,指出基礎數據流是否可讀取。

CanSeek

取得 Boolean 值,指出是否可搜尋基礎數據流。

CanTimeout

取得 Boolean 值,指出基礎數據流是否支援逾時。

CanWrite

取得 Boolean 值,指出基礎數據流是否可寫入。

CheckCertRevocationStatus

取得 Boolean 值,指出憑證驗證程序期間是否檢查證書吊銷清單。

CipherAlgorithm

取得值,這個值會識別這個 SslStream所使用的大量加密演算法。

CipherStrength

取得值,這個值會識別這個 SslStream所使用的加密演算法強度。

HashAlgorithm

取得用來產生訊息驗證碼 (MAC) 的演算法。

HashStrength

取得值,這個值會識別這個實例所使用的哈希演算法強度。

InnerStream

取得這個 AuthenticatedStream 用於傳送和接收數據的數據流。

(繼承來源 AuthenticatedStream)
IsAuthenticated

取得 Boolean 值,指出驗證是否成功。

IsEncrypted

取得 Boolean 值,指出這個 SslStream 是否使用數據加密。

IsMutuallyAuthenticated

取得 Boolean 值,指出是否已驗證伺服器和用戶端。

IsServer

取得 Boolean 值,指出這個 SslStream 所使用的連接本機端是否已驗證為伺服器。

IsSigned

取得 Boolean 值,指出是否使用此數據流傳送的數據已簽署。

KeyExchangeAlgorithm

取得這個 SslStream所使用的金鑰交換演算法。

KeyExchangeStrength

取得值,這個值會識別這個實例所使用的密鑰交換演演算法強度。

LeaveInnerStreamOpen

取得這個 AuthenticatedStream 用於傳送和接收數據的數據流是否已保持開啟狀態。

(繼承來源 AuthenticatedStream)
Length

取得基礎數據流的長度。

LocalCertificate

取得用來驗證本機端點的憑證。

NegotiatedApplicationProtocol

TLS 交握中交涉的應用程式通訊協定。

NegotiatedCipherSuite

取得為這個連接交涉的加密套件。

Position

取得或設定基礎數據流中的目前位置。

ReadTimeout

取得或設定等候數據的讀取作業區塊,以毫秒表示的時間量。

RemoteCertificate

取得用來驗證遠端端端點的憑證。

SslProtocol

取得值,這個值表示用來驗證此連線的安全性通訊協定。

TargetHostName

取得客戶端嘗試連線的伺服器名稱。 該名稱用於伺服器證書驗證。 它可以是 DNS 名稱或 IP 位址。

TransportContext

取得用於使用擴充保護進行驗證的 TransportContext

WriteTimeout

取得或設定寫入作業封鎖等候數據的時間量。

方法

AuthenticateAsClient(SslClientAuthenticationOptions)

用戶端呼叫以驗證伺服器,並選擇性地驗證客戶端-伺服器連線中的用戶端。

AuthenticateAsClient(String)

用戶端呼叫以驗證伺服器,並選擇性地驗證客戶端-伺服器連線中的用戶端。

AuthenticateAsClient(String, X509CertificateCollection, Boolean)

用戶端呼叫以驗證伺服器,並選擇性地驗證客戶端-伺服器連線中的用戶端。 驗證程式會使用指定的憑證集合,以及系統預設的 SSL 通訊協定。

AuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean)

用戶端呼叫以驗證伺服器,並選擇性地驗證客戶端-伺服器連線中的用戶端。 驗證程式會使用指定的憑證集合和 SSL 通訊協定。

AuthenticateAsClientAsync(SslClientAuthenticationOptions, CancellationToken)

用戶端呼叫以驗證伺服器,並選擇性地驗證客戶端-伺服器連線中的用戶端做為異步操作。 驗證程式會使用 sslClientAuthenticationOptions 屬性包中指定的資訊。

AuthenticateAsClientAsync(String)

用戶端呼叫以驗證伺服器,並選擇性地驗證客戶端-伺服器連線中的用戶端做為異步操作。

AuthenticateAsClientAsync(String, X509CertificateCollection, Boolean)

用戶端呼叫以驗證伺服器,並選擇性地驗證客戶端-伺服器連線中的用戶端做為異步操作。 驗證程式會使用指定的憑證集合和系統預設 SSL 通訊協定。

AuthenticateAsClientAsync(String, X509CertificateCollection, SslProtocols, Boolean)

用戶端呼叫以驗證伺服器,並選擇性地驗證客戶端-伺服器連線中的用戶端做為異步操作。 驗證程式會使用指定的憑證集合和 SSL 通訊協定。

AuthenticateAsServer(SslServerAuthenticationOptions)

由伺服器呼叫,以使用指定的憑證,在用戶端-伺服器連線中選擇性地驗證伺服器和用戶端。

AuthenticateAsServer(X509Certificate)

由伺服器呼叫,以使用指定的憑證,在用戶端-伺服器連線中選擇性地驗證伺服器和用戶端。

AuthenticateAsServer(X509Certificate, Boolean, Boolean)

由伺服器呼叫,以使用指定的憑證和需求,以及使用系統預設安全性通訊協定,在用戶端-伺服器連線中選擇性地驗證伺服器和用戶端。

AuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean)

由伺服器呼叫,以使用指定的憑證、需求和安全性通訊協定,在用戶端-伺服器連線中選擇性地驗證伺服器和用戶端。

AuthenticateAsServerAsync(ServerOptionsSelectionCallback, Object, CancellationToken)

由伺服器呼叫,以驗證伺服器,並選擇性地驗證客戶端-伺服器連線中的用戶端作為異步操作。 驗證程式會使用 optionsCallback傳回的資訊。

AuthenticateAsServerAsync(SslServerAuthenticationOptions, CancellationToken)

由伺服器呼叫,以驗證伺服器,並選擇性地驗證客戶端-伺服器連線中的用戶端作為異步操作。 驗證程式會使用 sslClientAuthenticationOptions 屬性包中指定的資訊。

AuthenticateAsServerAsync(X509Certificate)

由伺服器呼叫,以使用指定的憑證作為異步操作,在用戶端-伺服器連線中選擇性地驗證伺服器和用戶端。

AuthenticateAsServerAsync(X509Certificate, Boolean, Boolean)

由伺服器呼叫,以使用指定的憑證、需求和安全性通訊協定作為異步操作,在用戶端-伺服器聯機中選擇性地驗證伺服器和用戶端。

AuthenticateAsServerAsync(X509Certificate, Boolean, SslProtocols, Boolean)

由伺服器呼叫,以使用指定的憑證、需求和安全性通訊協定作為異步操作,在用戶端-伺服器聯機中選擇性地驗證伺服器和用戶端。

BeginAuthenticateAsClient(String, AsyncCallback, Object)

用戶端呼叫以開始異步操作,以驗證伺服器,並選擇性地驗證用戶端。

BeginAuthenticateAsClient(String, X509CertificateCollection, Boolean, AsyncCallback, Object)

用戶端呼叫以開始異步操作,以使用指定的憑證和系統預設安全性通訊協議來驗證伺服器,以及選擇性地驗證用戶端。

BeginAuthenticateAsClient(String, X509CertificateCollection, SslProtocols, Boolean, AsyncCallback, Object)

用戶端呼叫以開始異步操作,以使用指定的憑證和安全性通訊協議來驗證伺服器,以及選擇性地驗證用戶端。

BeginAuthenticateAsServer(X509Certificate, AsyncCallback, Object)

由伺服器呼叫以開始異步操作,以驗證用戶端,並選擇性地在用戶端-伺服器連線中驗證伺服器。

BeginAuthenticateAsServer(X509Certificate, Boolean, Boolean, AsyncCallback, Object)

由伺服器呼叫以開始異步操作,以使用指定的憑證和需求,以及系統預設安全性通訊協定來驗證伺服器,以及選擇性地驗證用戶端。

BeginAuthenticateAsServer(X509Certificate, Boolean, SslProtocols, Boolean, AsyncCallback, Object)

由伺服器呼叫以開始異步操作,以使用指定的憑證、需求和安全性通訊協定來驗證伺服器,以及選擇性地驗證用戶端。

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

開始異步讀取作業,從數據流讀取數據,並將其儲存在指定的陣列中。

BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

開始異步讀取作業。 (請考慮改用 ReadAsync(Byte[], Int32, Int32)

(繼承來源 Stream)
BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

開始異步寫入作業,將 Byte從指定的緩衝區寫入數據流。

BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)

開始異步寫入作業。 (請考慮改用 WriteAsync(Byte[], Int32, Int32)

(繼承來源 Stream)
Close()

關閉目前的數據流,並釋放與目前數據流相關聯的任何資源(例如套接字和檔句柄)。 請確定已正確處置數據流,而不是呼叫此方法。

(繼承來源 Stream)
CopyTo(Stream)

從目前的數據流讀取位元組,並將其寫入另一個數據流。 這兩個數據流位置都會依複製的位元元組數目進階。

(繼承來源 Stream)
CopyTo(Stream, Int32)

從目前的數據流讀取位元組,並使用指定的緩衝區大小將它們寫入另一個數據流。 這兩個數據流位置都會依複製的位元元組數目進階。

(繼承來源 Stream)
CopyToAsync(Stream)

以異步方式從目前的數據流讀取位元組,並將其寫入另一個數據流。 這兩個數據流位置都會依複製的位元元組數目進階。

(繼承來源 Stream)
CopyToAsync(Stream, CancellationToken)

使用指定的取消標記,以異步方式從目前數據流讀取位元組,並將其寫入另一個數據流。 這兩個數據流位置都會依複製的位元元組數目進階。

(繼承來源 Stream)
CopyToAsync(Stream, Int32)

使用指定的緩衝區大小,以異步方式從目前數據流讀取位元組,並將其寫入另一個數據流。 這兩個數據流位置都會依複製的位元元組數目進階。

(繼承來源 Stream)
CopyToAsync(Stream, Int32, CancellationToken)

使用指定的緩衝區大小和取消標記,以異步方式從目前數據流讀取位元組,並將其寫入另一個數據流。 這兩個數據流位置都會依複製的位元元組數目進階。

(繼承來源 Stream)
CreateObjRef(Type)

建立物件,其中包含產生用來與遠端物件通訊之 Proxy 所需的所有相關信息。

(繼承來源 MarshalByRefObject)
CreateWaitHandle()
已淘汰.
已淘汰.
已淘汰.

配置 WaitHandle 物件。

(繼承來源 Stream)
Dispose()

釋放 Stream所使用的所有資源。

(繼承來源 Stream)
Dispose(Boolean)

釋放 SslStream 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。

Dispose(Boolean)

釋放 AuthenticatedStream 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。

(繼承來源 AuthenticatedStream)
DisposeAsync()

以異步方式釋放 SslStream所使用的 Unmanaged 和 Managed 資源。

DisposeAsync()

以異步方式釋放 AuthenticatedStream所使用的 Unmanaged 和 Managed 資源。

(繼承來源 AuthenticatedStream)
EndAuthenticateAsClient(IAsyncResult)

結束擱置中的異步伺服器驗證作業,且先前呼叫 BeginAuthenticateAsClient

EndAuthenticateAsServer(IAsyncResult)

結束擱置中的異步客戶端驗證作業,此作業以先前呼叫 BeginAuthenticateAsClient開始。

EndRead(IAsyncResult)

結束異步讀取作業,且先前呼叫 BeginRead(Byte[], Int32, Int32, AsyncCallback, Object)

EndRead(IAsyncResult)

等候暫止的異步讀取完成。 (請考慮改用 ReadAsync(Byte[], Int32, Int32)

(繼承來源 Stream)
EndWrite(IAsyncResult)

結束以先前呼叫 BeginWrite(Byte[], Int32, Int32, AsyncCallback, Object)開始的異步寫入作業。

EndWrite(IAsyncResult)

結束異步寫入作業。 (請考慮改用 WriteAsync(Byte[], Int32, Int32)

(繼承來源 Stream)
Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Finalize()

釋放 SslStream所使用的所有資源。

Flush()

造成任何緩衝數據寫入基礎裝置。

FlushAsync()

以異步方式清除此數據流的所有緩衝區,並導致任何緩衝的數據寫入基礎裝置。

(繼承來源 Stream)
FlushAsync(CancellationToken)

以異步方式將任何緩衝的數據寫入基礎裝置。

FlushAsync(CancellationToken)

以異步方式清除此數據流的所有緩衝區、導致任何緩衝的數據寫入基礎裝置,並監視取消要求。

(繼承來源 Stream)
GetHashCode()

做為預設哈希函式。

(繼承來源 Object)
GetLifetimeService()
已淘汰.

擷取控制這個實例存留期原則的目前存留期服務物件。

(繼承來源 MarshalByRefObject)
GetType()

取得目前實例的 Type

(繼承來源 Object)
InitializeLifetimeService()
已淘汰.

取得存留期服務物件,以控制這個實例的存留期原則。

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 對象的淺層複本。

(繼承來源 MarshalByRefObject)
NegotiateClientCertificateAsync(CancellationToken)

交涉已驗證連線上的客戶端憑證。

ObjectInvariant()
已淘汰.

提供 Contract的支援。

(繼承來源 Stream)
Read(Byte[], Int32, Int32)

從這個數據流讀取數據,並將它儲存在指定的陣列中。

Read(Span<Byte>)

在衍生類別中覆寫時,從目前數據流讀取位元組序列,並將數據流中的位置依讀取的位元組數目往前移。

(繼承來源 Stream)
ReadAsync(Byte[], Int32, Int32)

以異步方式從目前數據流讀取位元組序列,並依讀取的位元元組數目將數據流中的位置往前移。

(繼承來源 Stream)
ReadAsync(Byte[], Int32, Int32, CancellationToken)

以異步方式從這個數據流讀取數據,並將其儲存在位元組陣列的指定範圍內。

ReadAsync(Byte[], Int32, Int32, CancellationToken)

以異步方式從目前數據流讀取位元組序列、依讀取的位元元組數目將數據流中的位置往前移,並監視取消要求。

(繼承來源 Stream)
ReadAsync(Memory<Byte>, CancellationToken)

以異步方式從這個數據流讀取數據,並將其儲存在指定的記憶體範圍中。

ReadAsync(Memory<Byte>, CancellationToken)

以異步方式從目前數據流讀取位元組序列、依讀取的位元元組數目將數據流中的位置往前移,並監視取消要求。

(繼承來源 Stream)
ReadAtLeast(Span<Byte>, Int32, Boolean)

從目前數據流讀取至少一個字節數目,並將數據流中的位置依讀取的位元組數目往前移。

(繼承來源 Stream)
ReadAtLeastAsync(Memory<Byte>, Int32, Boolean, CancellationToken)

以異步方式從目前數據流讀取至少一個字節數目、依讀取的位元組數目將數據流中的位置往前移,並監視取消要求。

(繼承來源 Stream)
ReadByte()

SslStream 讀取位元組,並將數據流中的位置往前移一個字節,或在數據流結尾處傳回 -1。

ReadByte()

從數據流讀取位元組,並在數據流結尾處將數據流中的位置往前移一個字節,或在數據流結尾傳回 -1。

(繼承來源 Stream)
ReadExactly(Byte[], Int32, Int32)

從目前數據流讀取 count 位元組數,並將位置往前移。

(繼承來源 Stream)
ReadExactly(Span<Byte>)

從目前的數據流讀取位元組,並將位置往前移,直到填入 buffer 為止。

(繼承來源 Stream)
ReadExactlyAsync(Byte[], Int32, Int32, CancellationToken)

以異步方式從目前數據流讀取 count 位元組數目、推進數據流中的位置,以及監視取消要求。

(繼承來源 Stream)
ReadExactlyAsync(Memory<Byte>, CancellationToken)

以異步方式從目前數據流讀取位元組、將數據流中的位置往前移,直到填入 buffer,並監視取消要求。

(繼承來源 Stream)
Seek(Int64, SeekOrigin)

擲回 NotSupportedException

SetLength(Int64)

設定基礎數據流的長度。

ShutdownAsync()

關閉此 SslStream。

ToString()

傳回表示目前 物件的字串。

(繼承來源 Object)
Write(Byte[])

將指定的數據寫入此數據流。

Write(Byte[], Int32, Int32)

使用指定的緩衝區和位移,將指定的 Byte數目寫入基礎數據流。

Write(ReadOnlySpan<Byte>)

在衍生類別中覆寫時,將位元組序列寫入目前數據流,並依寫入的位元組數目將這個數據流中的目前位置往前移。

(繼承來源 Stream)
WriteAsync(Byte[], Int32, Int32)

以異步方式將位元組序列寫入目前數據流,並依寫入的位元元組數目,將這個數據流中的目前位置往前移。

(繼承來源 Stream)
WriteAsync(Byte[], Int32, Int32, CancellationToken)

從位元組陣列的指定範圍,以異步方式將數據寫入基礎數據流。

WriteAsync(Byte[], Int32, Int32, CancellationToken)

以異步方式將位元組序列寫入至目前的數據流、依寫入的位元組數目將這個數據流中的目前位置往前移,並監視取消要求。

(繼承來源 Stream)
WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

以異步方式將數據從唯讀位元組記憶體範圍寫入基礎數據流。

WriteAsync(ReadOnlyMemory<Byte>, CancellationToken)

以異步方式將位元組序列寫入至目前的數據流、依寫入的位元組數目將這個數據流中的目前位置往前移,並監視取消要求。

(繼承來源 Stream)
WriteByte(Byte)

將位元組寫入數據流中的目前位置,並將數據流中的位置往前移一個字節。

(繼承來源 Stream)

擴充方法

CopyToAsync(Stream, PipeWriter, CancellationToken)

使用取消標記,以異步方式從 Stream 讀取位元組,並將其寫入指定的 PipeWriter

ConfigureAwait(IAsyncDisposable, Boolean)

設定如何執行從異步可處置專案傳回的工作等候。

適用於

另請參閱