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


C# StreamSocket.UpgradeToSslAsync方法代码示例

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


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

示例1: Connect


//.........这里部分代码省略.........
        /// The <see cref="Pop3Client"/> is already connected.
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was canceled via the cancellation token.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        /// <exception cref="Pop3CommandException">
        /// A POP3 command failed.
        /// </exception>
        /// <exception cref="Pop3ProtocolException">
        /// A POP3 protocol error occurred.
        /// </exception>
        public void Connect(Uri uri, CancellationToken cancellationToken)
        {
            CheckDisposed ();

            if (uri == null)
                throw new ArgumentNullException ("uri");

            if (!uri.IsAbsoluteUri)
                throw new ArgumentException ("The uri must be absolute.", "uri");

            if (IsConnected)
                throw new InvalidOperationException ("The Pop3Client is already connected.");

            var scheme = uri.Scheme.ToLowerInvariant ();
            var pops = scheme == "pops" || scheme == "pop3s";
            var port = uri.Port > 0 ? uri.Port : (pops ? 995 : 110);
            var query = uri.ParsedQuery ();
            #if !NETFX_CORE && !WINDOWS_APP && !WINDOWS_PHONE_APP
            var ipAddresses = Dns.GetHostAddresses (uri.DnsSafeHost);
            Socket socket = null;
            #endif
            Stream stream;
            string value;

            var starttls = !pops && (!query.TryGetValue ("starttls", out value) || Convert.ToBoolean (value));

            #if !NETFX_CORE && !WINDOWS_APP && !WINDOWS_PHONE_APP
            for (int i = 0; i < ipAddresses.Length; i++) {
                socket = new Socket (ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                cancellationToken.ThrowIfCancellationRequested ();

                try {
                    socket.Connect (ipAddresses[i], port);
                    break;
                } catch (Exception) {
                    if (i + 1 == ipAddresses.Length)
                        throw;
                }
            }

            if (pops) {
                var ssl = new SslStream (new NetworkStream (socket, true), false, ValidateRemoteCertificate);
                ssl.AuthenticateAsClient (uri.Host, ClientCertificates, SslProtocols.Default, true);
                stream = ssl;
            } else {
                stream = new NetworkStream (socket, true);
            }
            #else
            socket = new StreamSocket ();

            cancellationToken.ThrowIfCancellationRequested ();
            socket.ConnectAsync (new HostName (uri.DnsSafeHost), port.ToString (), pops ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket)
                .AsTask (cancellationToken)
                .GetAwaiter ()
                .GetResult ();

            stream = new DuplexStream (socket.InputStream.AsStreamForRead (), socket.OutputStream.AsStreamForWrite ());
            #endif

            probed = ProbedCapabilities.None;
            host = uri.Host;

            logger.LogConnect (uri);

            engine.Connect (new Pop3Stream (stream, logger), cancellationToken);
            engine.QueryCapabilities (cancellationToken);

            if (starttls && (engine.Capabilities & Pop3Capabilities.StartTLS) != 0) {
                SendCommand (cancellationToken, "STLS");

            #if !NETFX_CORE && !WINDOWS_APP && !WINDOWS_PHONE_APP
                var tls = new SslStream (stream, false, ValidateRemoteCertificate);
                tls.AuthenticateAsClient (uri.Host, ClientCertificates, SslProtocols.Tls, true);
                engine.Stream.Stream = tls;
            #else
                socket.UpgradeToSslAsync (SocketProtectionLevel.Tls12, new HostName (uri.DnsSafeHost))
                    .AsTask (cancellationToken)
                    .GetAwaiter ()
                    .GetResult ();
            #endif

                // re-issue a CAPA command
                engine.QueryCapabilities (cancellationToken);
            }
        }
开发者ID:EGrun,项目名称:MailKit,代码行数:101,代码来源:Pop3Client.cs

示例2: Connect


//.........这里部分代码省略.........
                throw new ArgumentException ("The uri must be absolute.", "uri");

            if (IsConnected)
                throw new InvalidOperationException ("The SmtpClient is already connected.");

            capabilities = SmtpCapabilities.None;
            authmechs.Clear ();
            MaxSize = 0;

            var smtps = uri.Scheme.ToLowerInvariant () == "smtps";
            var port = uri.Port > 0 ? uri.Port : (smtps ? 465 : 25);
            var query = uri.ParsedQuery ();
            SmtpResponse response = null;
            string value;

            var starttls = !smtps && (!query.TryGetValue ("starttls", out value) || Convert.ToBoolean (value));

            #if !NETFX_CORE
            var ipAddresses = Dns.GetHostAddresses (uri.DnsSafeHost);
            Socket socket = null;

            for (int i = 0; i < ipAddresses.Length; i++) {
                socket = new Socket (ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                cancellationToken.ThrowIfCancellationRequested ();

                try {
                    socket.Connect (ipAddresses[i], port);
                    localEndPoint = socket.LocalEndPoint;
                    break;
                } catch {
                    if (i + 1 == ipAddresses.Length)
                        throw;
                }
            }

            if (smtps) {
                var ssl = new SslStream (new NetworkStream (socket, true), false, ValidateRemoteCertificate);
                ssl.AuthenticateAsClient (uri.Host, ClientCertificates, SslProtocols.Default, true);
                stream = ssl;
            } else {
                stream = new NetworkStream (socket, true);
            }
            #else
            socket = new StreamSocket ();

            cancellationToken.ThrowIfCancellationRequested ();
            socket.ConnectAsync (new HostName (uri.DnsSafeHost), port.ToString (), smtps ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket)
                .AsTask (cancellationToken)
                .GetAwaiter ()
                .GetResult ();

            stream = new DuplexStream (socket.InputStream.AsStreamForRead (), socket.OutputStream.AsStreamForWrite ());
            #endif

            if (stream.CanTimeout) {
                stream.WriteTimeout = timeout;
                stream.ReadTimeout = timeout;
            }
            host = uri.Host;

            logger.LogConnect (uri);

            try {
                // read the greeting
                response = ReadResponse (cancellationToken);

                if (response.StatusCode != SmtpStatusCode.ServiceReady)
                    throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);

                // Send EHLO and get a list of supported extensions
                Ehlo (cancellationToken);

                if (starttls && (capabilities & SmtpCapabilities.StartTLS) != 0) {
                    response = SendCommand ("STARTTLS", cancellationToken);
                    if (response.StatusCode != SmtpStatusCode.ServiceReady)
                        throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);

            #if !NETFX_CORE
                    var tls = new SslStream (stream, false, ValidateRemoteCertificate);
                    tls.AuthenticateAsClient (uri.Host, ClientCertificates, SslProtocols.Tls, true);
                    stream = tls;
            #else
                    socket.UpgradeToSslAsync (SocketProtectionLevel.Tls12, new HostName (uri.DnsSafeHost))
                        .AsTask (cancellationToken)
                        .GetAwaiter ()
                        .GetResult ();
            #endif

                    // Send EHLO again and get the new list of supported extensions
                    Ehlo (cancellationToken);
                }

                IsConnected = true;
            } catch {
                stream.Dispose ();
                stream = null;
                throw;
            }
        }
开发者ID:richard2753,项目名称:MailKit,代码行数:101,代码来源:SmtpClient.cs

示例3: Connect


//.........这里部分代码省略.........

					if (LocalEndPoint != null)
						socket.Bind (LocalEndPoint);

					socket.Connect (ipAddresses[i], port);
					break;
				} catch (OperationCanceledException) {
					socket.Dispose ();
					socket = null;
					throw;
				} catch {
					socket.Dispose ();
					socket = null;

					if (i + 1 == ipAddresses.Length)
						throw;
				}
			}

			if (socket == null)
				throw new IOException (string.Format ("Failed to resolve host: {0}", host));

			this.host = host;

			if (options == SecureSocketOptions.SslOnConnect) {
				var ssl = new SslStream (new NetworkStream (socket, true), false, ValidateRemoteCertificate);
				ssl.AuthenticateAsClient (host, ClientCertificates, SslProtocols, true);
				stream = ssl;
			} else {
				stream = new NetworkStream (socket, true);
			}
#else
			var protection = options == SecureSocketOptions.SslOnConnect ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket;
			var socket = new StreamSocket ();

			try {
				cancellationToken.ThrowIfCancellationRequested ();
				socket.ConnectAsync (new HostName (host), port.ToString (), protection)
					.AsTask (cancellationToken)
					.GetAwaiter ()
					.GetResult ();
			} catch {
				socket.Dispose ();
				throw;
			}

			stream = new DuplexStream (socket.InputStream.AsStreamForRead (0), socket.OutputStream.AsStreamForWrite (0));
#endif

			if (stream.CanTimeout) {
				stream.WriteTimeout = timeout;
				stream.ReadTimeout = timeout;
			}

			ProtocolLogger.LogConnect (uri);

			Stream = new SmtpStream (stream, socket, ProtocolLogger);

			try {
				// read the greeting
				response = Stream.ReadResponse (cancellationToken);

				if (response.StatusCode != SmtpStatusCode.ServiceReady)
					throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);

				// Send EHLO and get a list of supported extensions
				Ehlo (cancellationToken);

				if (options == SecureSocketOptions.StartTls && (capabilities & SmtpCapabilities.StartTLS) == 0)
					throw new NotSupportedException ("The SMTP server does not support the STARTTLS extension.");

				if (starttls && (capabilities & SmtpCapabilities.StartTLS) != 0) {
					response = SendCommand ("STARTTLS", cancellationToken);
					if (response.StatusCode != SmtpStatusCode.ServiceReady)
						throw new SmtpCommandException (SmtpErrorCode.UnexpectedStatusCode, response.StatusCode, response.Response);

#if !NETFX_CORE
					var tls = new SslStream (stream, false, ValidateRemoteCertificate);
					tls.AuthenticateAsClient (host, ClientCertificates, SslProtocols, true);
					Stream.Stream = tls;
#else
					socket.UpgradeToSslAsync (SocketProtectionLevel.Tls12, new HostName (host))
						.AsTask (cancellationToken)
						.GetAwaiter ()
						.GetResult ();
#endif

					// Send EHLO again and get the new list of supported extensions
					Ehlo (cancellationToken);
				}

				connected = true;
			} catch {
				Stream.Dispose ();
				Stream = null;
				throw;
			}

			OnConnected ();
		}
开发者ID:erdonet,项目名称:MailKit,代码行数:101,代码来源:SmtpClient.cs

示例4: Connect


//.........这里部分代码省略.........
			for (int i = 0; i < ipAddresses.Length; i++) {
				socket = new Socket (ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);

				try {
					cancellationToken.ThrowIfCancellationRequested ();
					socket.Connect (ipAddresses[i], port);
					break;
				} catch (OperationCanceledException) {
					socket.Dispose ();
					throw;
				} catch {
					socket.Dispose ();

					if (i + 1 == ipAddresses.Length)
						throw;
				}
			}

			if (socket == null)
				throw new IOException (string.Format ("Failed to resolve host: {0}", host));
			
			engine.Uri = uri;

			if (options == SecureSocketOptions.SslOnConnect) {
				var ssl = new SslStream (new NetworkStream (socket, true), false, ValidateRemoteCertificate);
				ssl.AuthenticateAsClient (host, ClientCertificates, DefaultSslProtocols, true);
				stream = ssl;
			} else {
				stream = new NetworkStream (socket, true);
			}
#else
			var protection = options == SecureSocketOptions.SslOnConnect ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket;
			socket = new StreamSocket ();

			try {
				cancellationToken.ThrowIfCancellationRequested ();
				socket.ConnectAsync (new HostName (host), port.ToString (), protection)
					.AsTask (cancellationToken)
					.GetAwaiter ()
					.GetResult ();
			} catch {
				socket.Dispose ();
				socket = null;
				throw;
			}

			stream = new DuplexStream (socket.InputStream.AsStreamForRead (0), socket.OutputStream.AsStreamForWrite (0));
			engine.Uri = uri;
#endif

			if (stream.CanTimeout) {
				stream.WriteTimeout = timeout;
				stream.ReadTimeout = timeout;
			}

			ProtocolLogger.LogConnect (uri);

			engine.Connect (new ImapStream (stream, socket, ProtocolLogger), cancellationToken);

			try {
				// Only query the CAPABILITIES if the greeting didn't include them.
				if (engine.CapabilitiesVersion == 0)
					engine.QueryCapabilities (cancellationToken);
				
				if (options == SecureSocketOptions.StartTls && (engine.Capabilities & ImapCapabilities.StartTLS) == 0)
					throw new NotSupportedException ("The IMAP server does not support the STARTTLS extension.");
				
				if (starttls && (engine.Capabilities & ImapCapabilities.StartTLS) != 0) {
					var ic = engine.QueueCommand (cancellationToken, null, "STARTTLS\r\n");

					engine.Wait (ic);

					if (ic.Response == ImapCommandResponse.Ok) {
#if !NETFX_CORE
						var tls = new SslStream (stream, false, ValidateRemoteCertificate);
						tls.AuthenticateAsClient (host, ClientCertificates, DefaultSslProtocols, true);
						engine.Stream.Stream = tls;
#else
						socket.UpgradeToSslAsync (SocketProtectionLevel.Tls12, new HostName (host))
							.AsTask (cancellationToken)
							.GetAwaiter ()
							.GetResult ();
#endif

						// Query the CAPABILITIES again if the server did not include an
						// untagged CAPABILITIES response to the STARTTLS command.
						if (engine.CapabilitiesVersion == 1)
							engine.QueryCapabilities (cancellationToken);
					} else if (options == SecureSocketOptions.StartTls) {
						throw ImapCommandException.Create ("STARTTLS", ic);
					}
				}
			} catch {
				engine.Disconnect ();
				throw;
			}

			engine.Disconnected += OnEngineDisconnected;
			OnConnected ();
		}
开发者ID:yukine,项目名称:MailKit,代码行数:101,代码来源:ImapClient.cs

示例5: Connect


//.........这里部分代码省略.........
                throw new ArgumentException ("The uri must be absolute.", "uri");

            if (IsConnected)
                throw new InvalidOperationException ("The ImapClient is already connected.");

            var imaps = uri.Scheme.ToLowerInvariant () == "imaps";
            var port = uri.Port > 0 ? uri.Port : (imaps ? 993 : 143);
            var query = uri.ParsedQuery ();
            Stream stream;
            string value;

            var starttls = !imaps && (!query.TryGetValue ("starttls", out value) || Convert.ToBoolean (value));
            var compress = !imaps && (!query.TryGetValue ("compress", out value) || Convert.ToBoolean (value));

            #if !NETFX_CORE
            var ipAddresses = Dns.GetHostAddresses (uri.DnsSafeHost);
            Socket socket = null;

            for (int i = 0; i < ipAddresses.Length; i++) {
                socket = new Socket (ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                cancellationToken.ThrowIfCancellationRequested ();

                try {
                    socket.Connect (ipAddresses[i], port);
                    break;
                } catch {
                    if (i + 1 == ipAddresses.Length)
                        throw;
                }
            }

            if (imaps) {
                var ssl = new SslStream (new NetworkStream (socket, true), false, ValidateRemoteCertificate);
                ssl.AuthenticateAsClient (uri.Host, ClientCertificates, SslProtocols.Default, true);
                stream = ssl;
            } else {
                stream = new NetworkStream (socket, true);
            }
            #else
            socket = new StreamSocket ();

            cancellationToken.ThrowIfCancellationRequested ();
            socket.ConnectAsync (new HostName (uri.DnsSafeHost), port.ToString (), imaps ? SocketProtectionLevel.Tls12 : SocketProtectionLevel.PlainSocket)
                .AsTask (cancellationToken)
                .GetAwaiter ()
                .GetResult ();

            stream = new DuplexStream (socket.InputStream.AsStreamForRead (), socket.OutputStream.AsStreamForWrite ());
            #endif
            host = uri.Host;

            logger.LogConnect (uri);

            engine.Connect (new ImapStream (stream, logger), cancellationToken);

            // Only query the CAPABILITIES if the greeting didn't include them.
            if (engine.CapabilitiesVersion == 0)
                engine.QueryCapabilities (cancellationToken);

            if (starttls && (engine.Capabilities & ImapCapabilities.StartTLS) != 0) {
                var ic = engine.QueueCommand (cancellationToken, null, "STARTTLS\r\n");

                engine.Wait (ic);

                if (ic.Result == ImapCommandResult.Ok) {
            #if !NETFX_CORE
                    var tls = new SslStream (stream, false, ValidateRemoteCertificate);
                    tls.AuthenticateAsClient (uri.Host, ClientCertificates, SslProtocols.Tls, true);
                    engine.Stream.Stream = tls;
            #else
                    socket.UpgradeToSslAsync (SocketProtectionLevel.Tls12, new HostName (uri.DnsSafeHost))
                        .AsTask (cancellationToken)
                        .GetAwaiter ()
                        .GetResult ();
            #endif

                    // Query the CAPABILITIES again if the server did not include an
                    // untagged CAPABILITIES response to the STARTTLS command.
                    if (engine.CapabilitiesVersion == 1)
                        engine.QueryCapabilities (cancellationToken);
                }
            } else if (compress && (engine.Capabilities & ImapCapabilities.Compress) != 0) {
                var ic = engine.QueueCommand (cancellationToken, null, "COMPRESS DEFLATE\r\n");

                engine.Wait (ic);

                if (ic.Result == ImapCommandResult.Ok) {
                    var unzip = new DeflateStream (stream, CompressionMode.Decompress);
                    var zip = new DeflateStream (stream, CompressionMode.Compress);

                    engine.Stream.Stream = new DuplexStream (unzip, zip);

                    // Query the CAPABILITIES again if the server did not include an
                    // untagged CAPABILITIES response to the COMPRESS command.
                    if (engine.CapabilitiesVersion == 1)
                        engine.QueryCapabilities (cancellationToken);
                }
            }
        }
开发者ID:judicapo,项目名称:MailKit,代码行数:101,代码来源:ImapClient.cs

示例6: Connect

        public IAsyncOperation<string> Connect() {
            var window = CoreWindow.GetForCurrentThread();

            return Task.Run<string>(async () =>
            {
                try
                {
                    var socket = this.socket = new Windows.Networking.Sockets.StreamSocket();

                    await socket.ConnectAsync(new HostName("talk.google.com"), "5222", SocketProtectionLevel.PlainSocket);

                    await log(window, "connected!");

                    reader = new DataReader(socket.InputStream);
                    writer = new DataWriter(socket.OutputStream);

                    reader.InputStreamOptions = InputStreamOptions.Partial;

                    Write("<?xml version='1.0'?>\n<stream:stream to='" + server + "' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");

                    xmlStream = new XmlStream();
                    bool shouldRead = true;

                    xmlStream.SetCallback(async (promptRead, data) => {
                        await log(window, "data " + data);

                        if (promptRead)
                        {
                            if (shouldRead)
                            {
                                await log(window, "prompt read");

                                await reader.LoadAsync(4096);
                                var buffer = new byte[reader.UnconsumedBufferLength];
                                reader.ReadBytes(buffer);
                                await log(window, "in " + Encoding.UTF8.GetString(buffer, 0, buffer.Length));
                                xmlStream.Update(buffer, 0, buffer.Length);
                            }
                            else
                            {
                                await log(window, "read blocked");
                            }
                        }
                        else if (data.IndexOf("stream:features") != -1)
                        {
                            Write("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls' />");
                        }
                        else if (data.IndexOf("proceed") != -1)
                        {
                            await log(window, "SSL Strength: " + socket.Information.ProtectionLevel);

                            writer.DetachStream();
                            reader.DetachStream();

                            shouldRead = false;

                            if (server == "gmail.com")
                            {
                                await socket.UpgradeToSslAsync(SocketProtectionLevel.Ssl, new Windows.Networking.HostName("gmail.com"));
                            }
                            else
                            {
                                await socket.UpgradeToSslAsync(SocketProtectionLevel.Ssl, new Windows.Networking.HostName("talk.google.com"));
                            }

                            writer = new DataWriter(socket.OutputStream);
                            reader = new DataReader(socket.InputStream);

                            reader.InputStreamOptions = InputStreamOptions.Partial;

                            await log(window, "upgraded!");
                            await log(window, "SSL Strength: " + socket.Information.ProtectionLevel);

                            Write("<?xml version='1.0'?>\n<stream:stream to='" + server + "' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>");

                            xmlStream.SetCallback(async (shouldRead2, data2) =>
                            {
                                await log(window, "data " + data2);

                                if (shouldRead2)
                                {
                                    await reader.LoadAsync(4096);
                                    var buffer = new byte[reader.UnconsumedBufferLength];
                                    reader.ReadBytes(buffer);
                                    await log(window, "in " + Encoding.UTF8.GetString(buffer, 0, buffer.Length));
                                    xmlStream.Update(buffer, 0, buffer.Length);
                                }
                                else if (data2.Contains("X-GOOGLE-TOKEN"))
                                {
                                    var token = Convert.ToBase64String(Encoding.UTF8.GetBytes('\x00' + this.username + '\x00' + this.auth));
                                    Write("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='X-GOOGLE-TOKEN'>" + token + "</auth>");
                                }
                                else if (data2.Contains("failure"))
                                {
                                    if (Disconnect != null) Disconnect(this, "auth failure");
                                }
                                else if (data2.Contains("success"))
                                {
                                    var messageEvent = Message;

//.........这里部分代码省略.........
开发者ID:gchatapp,项目名称:GchatWin,代码行数:101,代码来源:Xmpp.cs

示例7: _sockConnection

        //------------------------------------------------------------------------------------------------------------------------
        SimpleActionResult _sockConnection(string RemoteHost, int RemotePort)
        {
            //declares
            bool isSecured = false;
            string sslProtocol = "";
            var result = new SimpleActionResult()
            {
                IsSuccessful = false,
                Message = "",
            };

            lock (this)
            {
                //create socket
#if NETFX
                _sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
#elif UNIVERSAL
                _sock = new StreamSocket();
#endif

                //Try to connect
                try
                {
                    //attemp connection
#if NETFX
                    _sock.Connect(RemoteHost, RemotePort);
#elif UNIVERSAL
                    SocketSetup?.Invoke(this, _sock);
                    _sock.Control.KeepAlive = true;
                    _sock.ConnectAsync(new Windows.Networking.HostName(RemoteHost), RemotePort.ToStringInvariant(), SocketProtectionLevel.PlainSocket).AsTask().Wait();
#endif
                }
                catch (Exception ex)
                {
                    DebugEx.TraceError(ex, "Connection Error");
                    result.Message = ex.Message;
                    try { Close("Connection Error"); } catch { }
                    return result;
                }


                //create network stream
#if NETFX
                //Stream _netstream = new BufferedStream(new NetworkStream(_sock, true));
                Stream _netstream = new NetworkStream(_sock, true);
#endif

                //Wrap with a secure stream?
                if (Secure)
                {
#if NETFX
                    //create ssl stream
                    var sslstream = new SslStream(_netstream, false);
#endif
                    //decide on certifacte server name
                    var remCertHostName = !string.IsNullOrWhiteSpace(CertificateServerName) ? CertificateServerName : RemoteHost;

                    try
                    {
#if NETFX            
                        //collect certificates
                        var certs = Yodiwo.Tools.Certificates.CollectCertificates();
                        if (CustomCertificates != null)
                            foreach (var c in CustomCertificates)
                                certs.Add(c);

                        //try authenticate
                        sslstream.AuthenticateAsClient(remCertHostName,
                                                        certs,
                                                        System.Security.Authentication.SslProtocols.Tls | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12,
                                                        true
                                                        );


                        //checks
                        if (!sslstream.IsAuthenticated)
                        {
                            DebugEx.Assert("Not authenticated");
                            throw new Exception("Not authenticated");
                        }
                        if (!sslstream.IsEncrypted)
                        {
                            DebugEx.Assert("No encryption");
                            throw new Exception("Not encryption");
                        }

                        //get info
                        isSecured = true;
                        sslProtocol = sslstream.SslProtocol.ToStringInvariant();

                        //use this stream from now on
                        _netstream = sslstream;
#elif UNIVERSAL
                        _sock.UpgradeToSslAsync(SocketProtectionLevel.Tls12, new Windows.Networking.HostName(remCertHostName)).AsTask().Wait();
                        var _isSecured = _sock.Information.ProtectionLevel == SocketProtectionLevel.Tls10 ||
                                     _sock.Information.ProtectionLevel == SocketProtectionLevel.Tls11 ||
                                     _sock.Information.ProtectionLevel == SocketProtectionLevel.Tls12;
                        if (!_isSecured)
                            throw new Exception("Connection not secured (" + _sock.Information.ProtectionLevel + ")");
//.........这里部分代码省略.........
开发者ID:yodiwo,项目名称:plegma,代码行数:101,代码来源:Client.cs


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