当前位置: 首页>>代码示例>>C#>>正文


C# SslStream.BeginRead方法代码示例

本文整理汇总了C#中System.Net.Security.SslStream.BeginRead方法的典型用法代码示例。如果您正苦于以下问题:C# SslStream.BeginRead方法的具体用法?C# SslStream.BeginRead怎么用?C# SslStream.BeginRead使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Security.SslStream的用法示例。


在下文中一共展示了SslStream.BeginRead方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ConnectSecure

        public void ConnectSecure(string hostname, int port, bool useEvents = true, bool validateServerCertificate = true)
        {
            if (Client.Connected)
            {
                throw new InvalidOperationException("Unable to connect: client is already connected");
            }

            Client.Connect(hostname, port);
            if (OnLocalPortKnown != null)
            {
                Task.Run(() => OnLocalPortKnown(((IPEndPoint)Client.Client.LocalEndPoint).Port));
            }
            var sslStream = new SslStream(Client.GetStream(), false, validateServerCertificate ? new RemoteCertificateValidationCallback(ValidateServerCertificate) : null, null);
            sslStream.AuthenticateAsClient(hostname);

            Log(string.Format("SSL Connection established: Cipher: {0}-bit {1}; KEX: {2} {3}-bit; Hash: {4} {5}-bit",
                sslStream.CipherStrength, sslStream.CipherAlgorithm,
                sslStream.KeyExchangeAlgorithm, sslStream.KeyExchangeStrength,
                sslStream.HashAlgorithm, sslStream.HashStrength));
            ConnectionStream = sslStream;

            readBuffer = new byte[Client.ReceiveBufferSize];
            if (useEvents)
            {
                EnterReadLoop();
                sslStream.BeginRead(readBuffer, 0, readBuffer.Length, ReadCallback, Client);
            }
        }
开发者ID:Baggykiin,项目名称:csnetlib2,代码行数:28,代码来源:NetLibClient.cs

示例2: Connect

        /// <summary>Connects the client to the server.</summary>
        /// <param name="serverPort">The port for the server to use for this connection</param>
        /// <param name="machineName">The host running the server application</param>
        /// <param name="serverName">The machine name for the server, must match the machine name in the server certificate</param>
        /// <param name="stream"></param>
        /// <param name="fileSize"></param>
        /// <param name="offset"></param>
        private void Connect(int serverPort, string machineName, string serverName, FileStream stream, long fileSize, long offset)
        {
            // Create a TCP/IP client socket.
            // Set up a temporary connection that is unencrypted, used to transfer the certificates?
            try {
                client = new TcpClient(machineName, serverPort);
                Debug.WriteLine("Client connected.");
            } catch (ArgumentNullException argExp) {
                throw new ConnectionException("Host or machine name is null", argExp);
            } catch (ArgumentOutOfRangeException argORExp) {
                throw new ConnectionException("The Port is incorrect", argORExp);
            } catch (SocketException argSExp) {
                throw new ConnectionException("There is a problem with the Socket", argSExp);
            }

            // Create an SSL stream that will close the client's stream.
            // TODO: The validate server certificate allways returns true
            //       If the validation fails we should ask the user to connect anyway
            sslStream = new SslStream(client.GetStream(),
                                      false,
                                      ValidateServerCertificate,
                                      null);

            // The server name must match the name on the server certificate.
            try {
                sslStream.AuthenticateAsClient(serverName);
            } catch (ArgumentNullException argExp) {
                throw new ConnectionException("Target host is null", argExp);
            } catch (AuthenticationException argExp) {
                throw new ConnectionException("The authentication failed and left this object in an unusable state.", argExp);
            } catch (InvalidOperationException argExp) {
                throw new ConnectionException("Authentication has already occurred or Server authentication using this SslStream was tried previously org Authentication is already in progress.", argExp);
            }

            // When we are connected we can now set up our receive mechanism
            var readBuffer = new byte[BUFFER_SIZE];
            var stateObj = new FileTransferStateObject();
            stateObj.fileSize = fileSize;
            stateObj.sslStream = sslStream;
            stateObj.target = stream;
            stateObj.transferBuffer = readBuffer;
            stateObj.transferOffset = offset;

            TimeOfLastNotify = DateTime.Now;

            sslStream.BeginRead(readBuffer, 0, readBuffer.Length, ReadCallback, stateObj);
        }
开发者ID:karlbohlmark,项目名称:SharpWired,代码行数:54,代码来源:BinarySecureSocket.cs

示例3: ConnectSecureAsync

        public async Task ConnectSecureAsync(string hostname, int port, bool useEvents = true, bool validateServerCertificate = true)
        {
            var t = Client.ConnectAsync(hostname, port);
            await t;
            if (OnLocalPortKnown != null)
            {
                t = Task.Run(() => OnLocalPortKnown(((IPEndPoint)Client.Client.LocalEndPoint).Port));
            }
            var sslStream = new SslStream(Client.GetStream(), false, validateServerCertificate ? new RemoteCertificateValidationCallback(ValidateServerCertificate) : null, null);
            var result = sslStream.AuthenticateAsClientAsync(hostname);
            ConnectionStream = sslStream;

            readBuffer = new byte[Client.ReceiveBufferSize];
            if (useEvents)
            {
                await result;
                Log(string.Format("SSL Connection established: Cipher: {1} ({0}-bit); KEX: {2} ({3}-bit); Hash: {4} ({5}-bit)",
                    sslStream.CipherStrength, sslStream.CipherAlgorithm,
                    sslStream.KeyExchangeAlgorithm, sslStream.KeyExchangeStrength,
                    sslStream.HashAlgorithm, sslStream.HashStrength));
                EnterReadLoop();
                sslStream.BeginRead(readBuffer, 0, readBuffer.Length, ReadCallback, Client);
            }
        }
开发者ID:Baggykiin,项目名称:csnetlib2,代码行数:24,代码来源:NetLibClient.cs

示例4: HandleSslConnect

        private static void HandleSslConnect(ConnectToRemoteState state)
        {
            var connectStreamWriter = new StreamWriter(state.ClientStream);
            connectStreamWriter.WriteLine("HTTP/1.0 200 Connection established");
            connectStreamWriter.WriteLine("Timestamp: {0}", DateTime.Now);
            connectStreamWriter.WriteLine("Proxy-agent: GOS Proxy Service");
            connectStreamWriter.WriteLine();
            connectStreamWriter.Flush();

            var sslStream = new SslStream(state.ClientStream, false);
            try
            {
                var certProvider = new CertificateProvider();

                bool created;
                var certificate = certProvider.LoadOrCreateCertificate(state.RemoteHost, out created);
                sslStream.AuthenticateAsServer(certificate, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true);
            }
            catch (Exception ex)
            {
                WriteLog(state.Session, 0, "ERR", ex.Message);
                sslStream.Close();
                state.ClientStream.Close();
                connectStreamWriter.Close();
                return;
            }

            var nstate = new ClientConnectionState
            {
                Session = state.Session,
                Client = state.Client,
                ClientStream = sslStream,
                ClientStreamBase = (NetworkStream)state.ClientStream,
                Buffer = new byte[Globals.BufferSize],
                MessageStream = new MemoryStream(),
                IsSsl = true,
            };

            try
            {
                sslStream.BeginRead(nstate.Buffer, 0, nstate.Buffer.Length, ReadFromClient.Run, nstate);
            }
            catch (Exception ex)
            {
                WriteLog(state.Session, 0, "ERR", ex.Message);
                sslStream.Close();
                state.ClientStream.Close();
            }
        }
开发者ID:JuergenGutsch,项目名称:async-proxy,代码行数:49,代码来源:ReadFromClient.cs

示例5: Assign

 /// <summary>
 ///     Assign a socket to this channel
 /// </summary>
 /// <param name="socket">Connected socket</param>
 /// <remarks>
 ///     the channel will start receive new messages as soon as you've called assign.
 /// </remarks>
 public void Assign(Socket socket)
 {
     _stream = _sslStreamBuilder.Build(this, socket);
     _stream.BeginRead(_readBuffer.Buffer, _readBuffer.Offset, _readBuffer.Capacity, OnReadCompleted, null);
 }
开发者ID:jorgenlidholm,项目名称:Griffin.Framework,代码行数:12,代码来源:SecureTcpChannel.cs

示例6: AcceptCallback

        private void AcceptCallback(IAsyncResult result)
        {
            // accept the client
            TcpListener listener = (TcpListener)result.AsyncState;
            TcpClient client = listener.EndAcceptTcpClient(result);
            ViewModel.TS_LogMessage("Client connected!");

            // set up SSL
            SslStream sslStream = new SslStream(client.GetStream(), false);
            sslStream.AuthenticateAsServer(ServerCertificate, false, SslProtocols.Tls, true);

            // create the user session
            ConnectionStateObject state = new ConnectionStateObject();
            state.client = client;
            state.stream = sslStream;

            // begin reading from the client
            ViewModel.TS_LogMessage("Awaiting client message...");
            sslStream.BeginRead(state.buffer, 0, state.buffer.Length, new AsyncCallback(ReceiveCallback), state);

            // start accepting again
            listener.BeginAcceptTcpClient(new AsyncCallback(AcceptCallback), listener);
        }
开发者ID:FuzzyWuzzie,项目名称:EncryptedStreamSample,代码行数:23,代码来源:Server.cs

示例7: Connect

        public bool Connect()
        {
            try
            {
                client = new TcpClient(serverEndPoint.Address.ToString(), serverEndPoint.Port);
            }
            catch (SocketException e)
            {
                Console.WriteLine("failed to connect to notification server: " + e.Message);
                if (e.InnerException != null) Console.WriteLine(e.InnerException);
                return false;
            }

            sslStream = new SslStream(client.GetStream(), false,
                new RemoteCertificateValidationCallback(ValidateRemoteCertificate));

            // Set timeouts
            sslStream.ReadTimeout = timeout;
            sslStream.WriteTimeout = timeout;

            try
            {
                sslStream.AuthenticateAsClient(serverEndPoint.Address.ToString(), clientCerts,
                    SslProtocols.Tls, false);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("authenticating notification SSL client failed, "
                    + e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("inner exception: "
                        + e.InnerException.Message);
                }
                client.Close();
                return false;
            }

            Console.WriteLine("ssl connection established to notification server");

            sslStream.BeginRead(recvBuf, 0, recvBuf.Length, new AsyncCallback(Receive), this);

            //generateNotification(NotificationMessage.Type.test, "Test.Notification-Wut");

            return true;
        }
开发者ID:apeape,项目名称:warehouse-frontend,代码行数:46,代码来源:NotificationClient.cs

示例8: Assign

        /// <summary>
        ///     Assign a socket to this channel
        /// </summary>
        /// <param name="socket">Connected socket</param>
        /// <remarks>
        ///     the channel will start receive new messages as soon as you've called assign.
        /// </remarks>
        public void Assign(Socket socket)
        {
            if (socket == null) throw new ArgumentNullException("socket");
            if (MessageReceived == null)
                throw new InvalidOperationException("Must handle the MessageReceived callback before invoking this method.");

            _stream = _sslStreamBuilder.Build(this, socket);
            _stream.BeginRead(_readBuffer.Buffer, _readBuffer.Offset, _readBuffer.Capacity, OnReadCompleted, null);
        }
开发者ID:krigans,项目名称:Griffin.Framework,代码行数:16,代码来源:SecureTcpChannel.cs

示例9: Connect

        /// <summary>Connects the client to the server.</summary>
        /// <param name="serverPort">The port for the server to use for this connection</param>
        /// <param name="machineName">The host running the server application</param>
        /// <param name="serverName">The machine name for the server, must match the machine name in the server certificate</param>
        private void Connect(int serverPort, string machineName, string serverName)
        {
            // Create a TCP/IP client socket.
            // Set up a temporary connection that is unencrypted, used to transfer the certificates?
            try {
                client = new TcpClient(machineName, serverPort);
                Debug.WriteLine("Client connected.");
            } catch (ArgumentNullException argExp) {
                throw new ConnectionException("HostOrMachineNameIsNull", argExp);
            } catch (ArgumentOutOfRangeException argORExp) {
                throw new ConnectionException("ThePortIsIncorrect", argORExp);
            } catch (SocketException argSExp) {
                var errorMessage = new StringBuilder();
                if (argSExp.ErrorCode == 11001) {
                    errorMessage.Append("HostNotFound");
                } else if (argSExp.ErrorCode == 10065) {
                    errorMessage.Append("NoRouteToTost");
                } else if (argSExp.ErrorCode == 10061) {
                    errorMessage.Append("ConnectionRefused");
                } else {
                    errorMessage.Append("ErrorNotRecognized" + " Socket error code: '" + argSExp.ErrorCode + "'");
                }

                //TODO: Add more error codes from: http://msdn2.microsoft.com/en-us/library/ms740668.aspx

                throw new ConnectionException(errorMessage.ToString(), argSExp);
            }

            // Create an SSL stream that will close the client's stream.
            // TODO: The validate server certificate allways returns true
            //      If the validation fails we should ask the user to connect anyway
            sslStream = new SslStream(client.GetStream(), false, ValidateServerCertificate, null);

            // The server name must match the name on the server certificate.
            try {
                sslStream.AuthenticateAsClient(serverName);
            } catch (ArgumentNullException argExp) {
                throw new ConnectionException("Target host is null", argExp);
            } catch (AuthenticationException argExp) {
                throw new ConnectionException("The authentication failed and left this object in an unusable state.", argExp);
            } catch (InvalidOperationException argExp) {
                throw new ConnectionException("Authentication has already occurred or Server authentication using this SslStream was tried previously org Authentication is already in progress.", argExp);
            }

            // When we are connected we can now set up our receive mechanism
            var readBuffer = new byte[buffer_size];
            sslStream.BeginRead(readBuffer, 0, readBuffer.Length, ReadCallback, readBuffer);
        }
开发者ID:karlbohlmark,项目名称:SharpWired,代码行数:52,代码来源:SecureSocket.cs

示例10: Main

        static void Main(string[] args)
        {
            MySocket socket = new MySocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
            socket.Connect(iep);
            MyNetworkStream stream = new MyNetworkStream(socket);
            SslStream sslStream = new SslStream(stream,false,new RemoteCertificateValidationCallback(ValidateServerCertificate),null );
            string msg = "hellodsffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffsdf,sdfwewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwfawwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww";
            byte[] data = Encoding.UTF8.GetBytes(msg);
            byte[] packet = new byte[6 + data.Length];
            byte[] lengthBytes = data.Length.ToCustomerBytes();
            Buffer.BlockCopy(lengthBytes, 0, packet, 2, lengthBytes.Length);
            Buffer.BlockCopy(data, 0, packet, 6, data.Length);
            sslStream.AuthenticateAsClient("127.0.0.1");
            Client client = new Client(sslStream);

            byte[] head = new byte[6];
            int contentLength = 50;
            byte[] contentLengthBytes = contentLength.ToCustomerBytes();
            Array.Copy(contentLengthBytes, 0, head, 2, contentLengthBytes.Length);
            client.Write(head);

            Thread.Sleep(1000);

            int firstPart = 25;
            client.Write(new byte[firstPart]);

            Thread.Sleep(1000);
            client.Write(new byte[contentLength - firstPart]);

            byte[] buff = new byte[1024];
            sslStream.BeginRead(buff, 0, buff.Length, ar =>
                {
                    int len=sslStream.EndRead(ar);
                    Console.WriteLine(len);
                }, null);
            Console.Read();
        }
开发者ID:RobertHu,项目名称:RobertUtil,代码行数:38,代码来源:Program.cs


注:本文中的System.Net.Security.SslStream.BeginRead方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。