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


C# SslStream.Dispose方法代码示例

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


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

示例1: CreateClient

        private static TcpConnection CreateClient(string Hostname, int port, bool IsSecure)
        {
            var client = new TcpClient(Hostname, port);
            var stream = (Stream)client.GetStream();

            if (IsSecure)
            {
                var sslStream = (SslStream)null;
                try
                {
                    sslStream = new SslStream(stream);
                    sslStream.AuthenticateAsClient(Hostname);
                    stream = (Stream)sslStream;
                }
                catch
                {
                    if (sslStream != null)
                        sslStream.Dispose();
                    throw;
                }
            }

            return new TcpConnection()
            {
                HostName = Hostname,
                port = port,
                IsSecure = IsSecure,
                TcpClient = client,
                ServerStreamReader = new CustomBinaryReader(stream, Encoding.ASCII),
                Stream = stream
            };
        }
开发者ID:davidchiew,项目名称:Titanium-Web-Proxy,代码行数:32,代码来源:TcpConnectionManager.cs

示例2: ConnectAsync

 public async Task<Stream> ConnectAsync(string host, int port, X509Certificate clientCert, CancellationToken cancel)
 {
     Stream lowerStream = null;
     SslStream sslStream = null;
     X509CertificateCollection certCollection = null;;
     if (clientCert != null)
     {
         certCollection = new X509CertificateCollection(new[] { clientCert });
     }
     try
     {
         lowerStream = await _connectionResolver.ConnectAsync(host, port, cancel);
         sslStream = new SslStream(lowerStream);
         await sslStream.AuthenticateAsClientAsync(host, certCollection, _protocols, checkCertificateRevocation: true);
         return sslStream;
     }
     catch (Exception)
     {
         if (sslStream != null)
         {
             sslStream.Dispose();
         }
         if (lowerStream != null)
         {
             lowerStream.Dispose();
         }
         throw;
     }
 }
开发者ID:Tratcher,项目名称:HTTP-SPEED-PLUS-MOBILITY,代码行数:29,代码来源:SslConnectionResolver.cs

示例3: TryConnectSsl

 private bool TryConnectSsl(Stream stream, out SslStream ssl)
 {
     ssl = new SslStream(stream, false, UserCertificateValidationCallback, UserCertificateSelectionCallback, EncryptionPolicy.RequireEncryption);
     try
     {
         ssl.AuthenticateAsClient("Local", null, SslProtocols.Tls12, false);
     }
     catch (Exception ex)
     {
         Log.Publish(MessageLevel.Info, "Authentication Failed", null, null, ex);
         ssl.Dispose();
         ssl = null;
         return false;
     }
     return true;
 }
开发者ID:GridProtectionAlliance,项目名称:openHistorian,代码行数:16,代码来源:SecureStreamClientBase.cs

示例4: Connect

		/// <summary>
		/// Establishes a connection to the specified SMTP or SMTP/S server.
		/// </summary>
		/// <remarks>
		/// <para>Establishes a connection to the specified SMTP or SMTP/S server.</para>
		/// <para>If the <paramref name="port"/> has a value of <c>0</c>, then the
		/// <paramref name="options"/> parameter is used to determine the default port to
		/// connect to. The default port used with <see cref="SecureSocketOptions.SslOnConnect"/>
		/// is <c>465</c>. All other values will use a default port of <c>25</c>.</para>
		/// <para>If the <paramref name="options"/> has a value of
		/// <see cref="SecureSocketOptions.Auto"/>, then the <paramref name="port"/> is used
		/// to determine the default security options. If the <paramref name="port"/> has a value
		/// of <c>465</c>, then the default options used will be
		/// <see cref="SecureSocketOptions.SslOnConnect"/>. All other values will use
		/// <see cref="SecureSocketOptions.StartTlsWhenAvailable"/>.</para>
		/// <para>Once a connection is established, properties such as
		/// <see cref="AuthenticationMechanisms"/> and <see cref="Capabilities"/> will be
		/// populated.</para>
		/// <note type="note">The connection established by any of the
		/// <a href="Overload_MailKit_Net_Smtp_SmtpClient_Connect.htm">Connect</a>
		/// methods may be re-used if an application wishes to send multiple messages
		/// to the same SMTP server. Since connecting and authenticating can be expensive
		/// operations, re-using a connection can significantly improve performance when
		/// sending a large number of messages to the same SMTP server over a short
		/// period of time.</note>
		/// </remarks>
		/// <example>
		/// <code language="c#" source="Examples\SmtpExamples.cs" region="SendMessage"/>
		/// </example>
		/// <param name="host">The host name to connect to.</param>
		/// <param name="port">The port to connect to. If the specified port is <c>0</c>, then the default port will be used.</param>
		/// <param name="options">The secure socket options to when connecting.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="host"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="port"/> is not between <c>0</c> and <c>65535</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// The <paramref name="host"/> is a zero-length string.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="SmtpClient"/> has been disposed.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// The <see cref="SmtpClient"/> is already connected.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// <paramref name="options"/> was set to
		/// <see cref="MailKit.Security.SecureSocketOptions.StartTls"/>
		/// and the SMTP server does not support the STARTTLS extension.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled.
		/// </exception>
		/// <exception cref="System.Net.Sockets.SocketException">
		/// A socket error occurred trying to connect to the remote host.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="SmtpCommandException">
		/// An SMTP command failed.
		/// </exception>
		/// <exception cref="SmtpProtocolException">
		/// An SMTP protocol error occurred.
		/// </exception>
		public override void Connect (string host, int port = 0, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (host == null)
				throw new ArgumentNullException (nameof (host));

			if (host.Length == 0)
				throw new ArgumentException ("The host name cannot be empty.", nameof (host));

			if (port < 0 || port > 65535)
				throw new ArgumentOutOfRangeException (nameof (port));
			
			CheckDisposed ();

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

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

			SmtpResponse response;
			Stream stream;
			bool starttls;
			Uri uri;

			ComputeDefaultValues (host, ref port, ref options, out uri, out starttls);

#if !NETFX_CORE
#if COREFX
			var ipAddresses = Dns.GetHostAddressesAsync (uri.DnsSafeHost).GetAwaiter ().GetResult ();
#else
			var ipAddresses = Dns.GetHostAddresses (uri.DnsSafeHost);
//.........这里部分代码省略.........
开发者ID:jstedfast,项目名称:MailKit,代码行数:101,代码来源:SmtpClient.cs

示例5: Connect

        public bool Connect(int maxTryCount = 5)
        {
            TcpClient newTcpClient = null;
            SslStream newSslStream = null;
            int tryCount = 0;
            bool loggedIn = false;

            while (tryCount < maxTryCount && !loggedIn)
            {
                ++tryCount;
                bool retrying = tryCount > 1 ? true : false;

                if (retrying)
                {
                    Debug.WriteLine("ImapClient.Connect(): Trying to connect to " + Account.ImapServerName + ":" + Account.ImapPortNumber + "..." + tryCount);
                    if (newTcpClient != null)
                    {
                        newTcpClient.Close();
                    }
                    if (newSslStream != null)
                    {
                        newSslStream.Dispose();
                    }
                    Thread.Sleep(1000);
                }

                bool connected = false;
                try
                {
                    newTcpClient = new TcpClient();
                    var result = newTcpClient.BeginConnect(Account.ImapServerName, Account.ImapPortNumber, null, null);
                    var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5));
                    if (success && newTcpClient.Connected)
                    {
                        connected = true;
                        if (retrying)
                        {
                            Debug.WriteLine("ImapClient.Connect(): Connection succeeded.");
                        }
                    }
                    newTcpClient.EndConnect(result);
                }
                catch (Exception e)
                {
                    Error = e.Message;
                    Debug.WriteLine("ImapClient.Connect(): Exception occured while trying to connect to " + Account.ImapServerName + ":" + Account.ImapPortNumber + ".\n" + Error);
                    newTcpClient.Close();
                    return false;
                }

                if (!connected)
                {
                    if (tryCount < maxTryCount)
                    {
                        // Retry connecting.
                        continue;
                    }
                    else
                    {
                        Error = "Unable to connect to " + Account.ImapServerName + ":" + Account.ImapPortNumber;
                        Debug.WriteLine("ImapClient.Connect(): " + Error);
                        newTcpClient.Close();
                        return false;
                    }
                }

                // Now we're connected through TCP. Try to authenticate through SSL.
                try
                {
                    newSslStream = new SslStream(newTcpClient.GetStream(), false);
                    newSslStream.AuthenticateAsClient(Account.ImapServerName);
                }
                catch (Exception e)
                {
                    Error = e.Message;
                    Debug.WriteLine("ImapClient.Connect(): Exception occured while creating SSL stream to " + Account.ImapServerName + ":" + Account.ImapPortNumber + ".\n" + Error);
                    newTcpClient.Close();
                    return false;
                }

                // Now we're on SSL. Try to log in.
                if (retrying)
                {
                    Debug.WriteLine("ImapClient.Connect(): Logging in to " + Account.ImapServerName + "(" + Account.AccountName + ").");
                }

                newSslStream.ReadTimeout = 5000;  // For synchronous read calls.
                if (TryLogin(newSslStream))
                {
                    loggedIn = true;
                    if (retrying)
                    {
                        Debug.WriteLine("ImapClient.Connect(): Login succeeded.");
                    }
                }
            }

            if (!loggedIn)
            {
                // Reached max retry count. Clean up and return.
//.........这里部分代码省略.........
开发者ID:uml-dc2-2016-spring,项目名称:dc16-MEClient,代码行数:101,代码来源:ImapClient.cs

示例6: RunClient

        public MFTestResults RunClient()
        {
             MFTestResults testResult = MFTestResults .Pass;
            try
            {
                if (ipAddress == null)
                    Console.WriteLine("IpAddress must be initialized before calling RunClient()");
                else
                    serverEp = new IPEndPoint(ipAddress, port);

                IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress localAddr = null;
                foreach (IPAddress addr in hostEntry.AddressList)
                {
                    if (addr.AddressFamily == AddressFamily.InterNetwork)
                    {
                        localAddr = addr;
                    }
                }

                IPEndPoint localEnpoint = new IPEndPoint(localAddr, port);

                Console.WriteLine("Connect to IPAddress: " + serverEp.Address.ToString() + " Port Number: " + serverEp.Port.ToString());

                // Create a TCP/IP client socket.
                bool connected = false;
                int retries = 0;
                while (!connected)
                {
                    try
                    {

                        clientSocket = new TcpClient(localEnpoint);
                        clientSocket.Connect(serverEp);
                        connected = true;
                    }
                    catch { }

                    Thread.Sleep(1000);
                    retries++;
                    if (retries > 20)
                    {
                        Console.WriteLine("Tried to connect 20 times without success.  Failing test.");
                        return MFTestResults.Fail;
                    }
                }

                // Create an SSL stream that will close the client's stream.
                sslClient = new SslStream(clientSocket.GetStream());

                Console.WriteLine("Calling AuthenticateAsClient()");
                // The server name must match the name on the server certificate.
                sslClient.AuthenticateAsClient(targetHost, certificateCollection, sslProtocols, false);

                // Send hello message to the server. 
                byte[] message = Encoding.UTF8.GetBytes(messageSent);
                sslClient.Write(message, 0, message.Length);
                Console.WriteLine("Sent:     " + messageSent);

                // Read message from the server.
                messageReceived = ReadMessage(sslClient);
                Console.WriteLine("Received: " + messageReceived);

                if (messageSent != messageReceived)
                    testResult = MFTestResults.Fail;

            }
            catch (SocketException e)
            {
                if (!expectedException)
                    testResult = MFTestResults.Fail;
                Console.WriteLine("ErrorCode: " + e.ErrorCode);
                Console.WriteLine("An exception occurred: " + e.Message);
            }
            catch (Exception e)
            {
                if (!expectedException)
                    testResult = MFTestResults.Fail;
                Console.WriteLine("An exception occurred: " + e.Message);
            }
            finally
            {
                if (sslClient != null)
                {
                    Thread.Sleep(50);
                    sslClient.Dispose();
                    sslClient = null;
                }
                if (clientSocket != null)
                {
                    clientSocket.Close();
                    clientSocket = null;
                }
            }
            return testResult;
        }
开发者ID:aura1213,项目名称:netmf-interpreter,代码行数:96,代码来源:SslClient.cs

示例7: ConnectSync

        private bool ConnectSync(string sHost, int nPort)
        {
            bool result = false;
            try
            {
                var imapServer = new TcpClient(sHost, nPort);
                _imapSslStream = new SslStream(imapServer.GetStream(), false, ValidateServerCertificate, null);

                try
                {
                    _imapSslStream.AuthenticateAsClient(sHost, null, SslProtocols.Default, false);
                }
                catch (AuthenticationException authEx)
                {
                    _logger.Warn(authEx, "Authentication failed");
                    _imapSslStream.Dispose();
                    imapServer.Close();
                    return false;
                }
                _imapSslStreamReader = new StreamReader(_imapSslStream);
                var text = _imapSslStreamReader.ReadLine();
                if (text != null && text.StartsWith("* OK"))
                {
                    result = Capability();
                }
            }
            catch (IOException ioEx)
            {
                _logger.Warn(ioEx, "Failed to connect");
            }
            return result;
        }
开发者ID:CallWall,项目名称:CallWall.Web,代码行数:32,代码来源:ImapClient.cs

示例8: TlsConnect

 // guarantees to close the socket on error
 public static void TlsConnect(Socket sock, string host, RemoteCertificateValidationCallback rcvc, Action<Exception,SslStream> cb)
 {
     SslStream ssl = null;
     try {
         ssl = new SslStream (new NetworkStream (sock, true), false, rcvc);
         ssl.BeginAuthenticateAsClient (host, (ar) => {
             try {
                 ssl.EndAuthenticateAsClient (ar);
             } catch (Exception ex) {
                 ssl.Dispose ();
                 sock.Dispose ();
                 cb (ex, null);
                 return;
             }
             cb (null, ssl);
         }, null);
     } catch (Exception ex) {
         if (ssl != null)
             ssl.Dispose ();
         sock.Dispose ();
         cb (ex, null);
     }
 }
开发者ID:dnorman,项目名称:scamp,代码行数:24,代码来源:NetUtil.cs

示例9: Run

        public void Run(ApplePushChannelSettings settings, CancellationToken cancelToken)
        {
            var encoding = Encoding.ASCII;

            var certificate = settings.Certificate;

            var certificates = new X509CertificateCollection();
            certificates.Add(certificate);

            var client = new TcpClient(settings.FeedbackHost, settings.FeedbackPort);

            var stream = new SslStream(client.GetStream(), true,
                (sender, cert, chain, sslErrs) => { return true; },
                (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return certificate; });

            stream.AuthenticateAsClient(settings.FeedbackHost, certificates, System.Security.Authentication.SslProtocols.Ssl3, false);

            //Set up
            byte[] buffer = new byte[38];
            int recd = 0;
            DateTime minTimestamp = DateTime.Now.AddYears(-1);

            //Get the first feedback
            recd = stream.Read(buffer, 0, buffer.Length);

            //Continue while we have results and are not disposing
            while (recd > 0 && !cancelToken.IsCancellationRequested)
            {
                try
                {

                    //Get our seconds since 1970 ?
                    byte[] bSeconds = new byte[4];
                    byte[] bDeviceToken = new byte[32];

                    Array.Copy(buffer, 0, bSeconds, 0, 4);

                    //Check endianness
                    if (BitConverter.IsLittleEndian)
                        Array.Reverse(bSeconds);

                    int tSeconds = BitConverter.ToInt32(bSeconds, 0);

                    //Add seconds since 1970 to that date, in UTC
                    var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(tSeconds);

                    //flag to allow feedback times in UTC or local, but default is local
                    if (!settings.FeedbackTimeIsUTC)
                        timestamp = timestamp.ToLocalTime();

                    //Now copy out the device token
                    Array.Copy(buffer, 6, bDeviceToken, 0, 32);

                    var deviceToken = BitConverter.ToString(bDeviceToken).Replace("-", "").ToLower().Trim();

                    //Make sure we have a good feedback tuple
                    if (deviceToken.Length == 64
                        && timestamp > minTimestamp)
                    {
                        //Raise event
                        RaiseFeedbackReceived(deviceToken, timestamp);
                    }

                }
                catch { }

                //Clear our array to reuse it
                Array.Clear(buffer, 0, buffer.Length);

                //Read the next feedback
                recd = stream.Read(buffer, 0, buffer.Length);
            }

            try
            {
                stream.Close ();
                stream.Dispose();
            }
            catch { }

            try
            {
                client.Client.Shutdown (SocketShutdown.Both);
                client.Client.Dispose ();
            }
            catch { }

            try { client.Close (); } catch { }
        }
开发者ID:Jaylee89,项目名称:demo,代码行数:89,代码来源:FeedbackService.cs

示例10: HandleClient

        private static void HandleClient(TcpClient client)
        {
            Stream clientStream = client.GetStream();
            var clientStreamReader = new CustomBinaryReader(clientStream, Encoding.ASCII);
            var clientStreamWriter = new StreamWriter(clientStream);

            Uri httpRemoteUri;
            try
            {
                //read the first line HTTP command

                var httpCmd = clientStreamReader.ReadLine();

                if (string.IsNullOrEmpty(httpCmd))
                {
                    Dispose(client, clientStream, clientStreamReader, clientStreamWriter, null);
                    return;
                }

                //break up the line into three components (method, remote URL & Http Version)
                var httpCmdSplit = httpCmd.Split(SpaceSplit, 3);

                var httpVerb = httpCmdSplit[0];

                if (httpVerb.ToUpper() == "CONNECT")
                    httpRemoteUri = new Uri("http://" + httpCmdSplit[1]);
                else
                    httpRemoteUri = new Uri(httpCmdSplit[1]);

                var httpVersion = httpCmdSplit[2];

                var excluded = ExcludedHttpsHostNameRegex.Any(x => Regex.IsMatch(httpRemoteUri.Host, x));

                //Client wants to create a secure tcp tunnel (its a HTTPS request)
                if (httpVerb.ToUpper() == "CONNECT" && !excluded && httpRemoteUri.Port == 443)
                {
                    httpRemoteUri = new Uri("https://" + httpCmdSplit[1]);
                    clientStreamReader.ReadAllLines();

                    WriteConnectResponse(clientStreamWriter, httpVersion);

                    var certificate = CertManager.CreateCertificate(httpRemoteUri.Host);

                    SslStream sslStream = null;

                    try
                    {
                        sslStream = new SslStream(clientStream, true);
                        //Successfully managed to authenticate the client using the fake certificate
                        sslStream.AuthenticateAsServer(certificate, false,
                            SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, false);

                        clientStreamReader = new CustomBinaryReader(sslStream, Encoding.ASCII);
                        clientStreamWriter = new StreamWriter(sslStream);
                        //HTTPS server created - we can now decrypt the client's traffic
                        clientStream = sslStream;
                    }

                    catch
                    {
                        if (sslStream != null)
                            sslStream.Dispose();

                        Dispose(client, clientStream, clientStreamReader, clientStreamWriter, null);
                        return;
                    }


                    httpCmd = clientStreamReader.ReadLine();

                }
                else if (httpVerb.ToUpper() == "CONNECT")
                {
                    clientStreamReader.ReadAllLines();
                    WriteConnectResponse(clientStreamWriter, httpVersion);
                    TcpHelper.SendRaw(clientStreamReader.BaseStream, null, null, httpRemoteUri.Host, httpRemoteUri.Port,
                        false);
                    Dispose(client, clientStream, clientStreamReader, clientStreamWriter, null);
                    return;
                }

                //Now create the request
                HandleHttpSessionRequest(client, httpCmd, clientStream, clientStreamReader, clientStreamWriter,
                    httpRemoteUri.Scheme == Uri.UriSchemeHttps ? httpRemoteUri.OriginalString : null);
            }
            catch
            {
                Dispose(client, clientStream, clientStreamReader, clientStreamWriter, null);
            }
        }
开发者ID:davidchiew,项目名称:Titanium-Web-Proxy,代码行数:90,代码来源:RequestHandler.cs

示例11: Connect

		/// <summary>
		/// Establish a connection to the specified IMAP server.
		/// </summary>
		/// <remarks>
		/// <para>Establishes a connection to the specified IMAP or IMAP/S server.</para>
		/// <para>If the <paramref name="port"/> has a value of <c>0</c>, then the
		/// <paramref name="options"/> parameter is used to determine the default port to
		/// connect to. The default port used with <see cref="SecureSocketOptions.SslOnConnect"/>
		/// is <c>993</c>. All other values will use a default port of <c>143</c>.</para>
		/// <para>If the <paramref name="options"/> has a value of
		/// <see cref="SecureSocketOptions.Auto"/>, then the <paramref name="port"/> is used
		/// to determine the default security options. If the <paramref name="port"/> has a value
		/// of <c>993</c>, then the default options used will be
		/// <see cref="SecureSocketOptions.SslOnConnect"/>. All other values will use
		/// <see cref="SecureSocketOptions.StartTlsWhenAvailable"/>.</para>
		/// <para>Once a connection is established, properties such as
		/// <see cref="AuthenticationMechanisms"/> and <see cref="Capabilities"/> will be
		/// populated.</para>
		/// </remarks>
		/// <example>
		/// <code language="c#" source="Examples\ImapExamples.cs" region="DownloadMessages"/>
		/// </example>
		/// <param name="host">The host name to connect to.</param>
		/// <param name="port">The port to connect to. If the specified port is <c>0</c>, then the default port will be used.</param>
		/// <param name="options">The secure socket options to when connecting.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="host"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="port"/> is not between <c>0</c> and <c>65535</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// The <paramref name="host"/> is a zero-length string.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// The <see cref="ImapClient"/> is already connected.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// <paramref name="options"/> was set to
		/// <see cref="MailKit.Security.SecureSocketOptions.StartTls"/>
		/// and the IMAP server does not support the STARTTLS extension.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.Net.Sockets.SocketException">
		/// A socket error occurred trying to connect to the remote host.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// An IMAP protocol error occurred.
		/// </exception>
		public override void Connect (string host, int port = 0, SecureSocketOptions options = SecureSocketOptions.Auto, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (host == null)
				throw new ArgumentNullException (nameof (host));

			if (host.Length == 0)
				throw new ArgumentException ("The host name cannot be empty.", nameof (host));

			if (port < 0 || port > 65535)
				throw new ArgumentOutOfRangeException (nameof (port));

			CheckDisposed ();

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

			Stream stream;
			bool starttls;
			Uri uri;

			ComputeDefaultValues (host, ref port, ref options, out uri, out starttls);

#if !NETFX_CORE
#if COREFX
			var ipAddresses = Dns.GetHostAddressesAsync (uri.DnsSafeHost).GetAwaiter ().GetResult ();
#else
			var ipAddresses = Dns.GetHostAddresses (uri.DnsSafeHost);
#endif
			Socket socket = null;

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

				try {
					cancellationToken.ThrowIfCancellationRequested ();

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

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

示例12: Run

		public void Run(ApplePushChannelSettings settings, CancellationToken cancelToken)
		{
			var encoding = Encoding.ASCII;

			var certificate = settings.Certificate;

			var certificates = new X509CertificateCollection();
			certificates.Add(certificate);


			var client = new TcpClient(settings.FeedbackHost, settings.FeedbackPort);

			var stream = new SslStream(client.GetStream(), true,
				(sender, cert, chain, sslErrs) => { return true; },
				(sender, targetHost, localCerts, remoteCert, acceptableIssuers) => { return certificate; });

			stream.AuthenticateAsClient(settings.FeedbackHost, certificates, System.Security.Authentication.SslProtocols.Tls, false);


			//Set up
			byte[] buffer = new byte[1482];
			int bufferIndex = 0;
			int bufferLevel = 0;
			int completePacketSize = 4 + 2 + 32;
			int recd = 0;
			DateTime minTimestamp = DateTime.Now.AddYears(-1);

			//Get the first feedback
			recd = stream.Read(buffer, 0, buffer.Length);

			//Continue while we have results and are not disposing
			while (recd > 0 && !cancelToken.IsCancellationRequested)
			{
				//Update how much data is in the buffer, and reset the position to the beginning
				bufferLevel += recd;
				bufferIndex = 0;

				try
				{
					//Process each complete notification "packet" available in the buffer
					while (bufferLevel - bufferIndex >= completePacketSize)
					{
						//Get our seconds since 1970 ?
						byte[] bSeconds = new byte[4];
						byte[] bDeviceToken = new byte[32];

						Array.Copy(buffer, bufferIndex, bSeconds, 0, 4);

						//Check endianness
						if (BitConverter.IsLittleEndian)
							Array.Reverse(bSeconds);

						int tSeconds = BitConverter.ToInt32(bSeconds, 0);

						//Add seconds since 1970 to that date, in UTC
						var timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(tSeconds);

						//flag to allow feedback times in UTC or local, but default is local
						if (!settings.FeedbackTimeIsUTC)
							timestamp = timestamp.ToLocalTime();

						//Now copy out the device token
						Array.Copy(buffer, bufferIndex + 6, bDeviceToken, 0, 32);

						var deviceToken = BitConverter.ToString(bDeviceToken).Replace("-", "").ToLower().Trim();

						//Make sure we have a good feedback tuple
						if (deviceToken.Length == 64
							&& timestamp > minTimestamp)
						{
							//Raise event
							try
							{
								RaiseFeedbackReceived(deviceToken, timestamp);
							}
							catch { }
						}

						//Keep track of where we are in the received data buffer
						bufferIndex += completePacketSize;
					}
				}
				catch { }

				//Figure out how much data we have left over in the buffer still
				bufferLevel -= bufferIndex;

				//Copy any leftover data in the buffer to the start of the buffer
				if (bufferLevel > 0)
					Array.Copy(buffer, bufferIndex, buffer, 0, bufferLevel);

				//Read the next feedback
				recd = stream.Read(buffer, bufferLevel, buffer.Length - bufferLevel);
			}

			try
			{
				stream.Close ();
				stream.Dispose();
			}
//.........这里部分代码省略.........
开发者ID:greg84,项目名称:PushSharp,代码行数:101,代码来源:FeedbackService.cs

示例13: MakeServerStreamAsync

        public static async Task<EpoxyNetworkStream> MakeServerStreamAsync(
            Socket socket,
            EpoxyServerTlsConfig tlsConfig,
            Logger logger)
        {
            Stream serverStream;
            var networkStream = new NetworkStream(socket, ownsSocket: false);

            if (tlsConfig == null)
            {
                serverStream = networkStream;
            }
            else
            {
                const bool leaveInnerStreamOpen = false;

                var sslStream = new SslStream(
                    networkStream,
                    leaveInnerStreamOpen,
                    MakeServerCertificateValidationCallback(tlsConfig, logger));

                await sslStream.AuthenticateAsServerAsync(
                    tlsConfig.Certificate,
                    tlsConfig.ClientCertificateRequired,
                    enabledSslProtocols: AllowedTlsProtocols,
                    checkCertificateRevocation: tlsConfig.CheckCertificateRevocation);

                if (tlsConfig.ClientCertificateRequired && !sslStream.IsMutuallyAuthenticated)
                {
                    sslStream.Dispose();
                    throw new AuthenticationException("Mutual authentication was required, but it could not be performed.");
                }

                logger.Site().Debug(
                    "Authenticated connection from {0}. Mutually authenticated?: {1}",
                    socket.RemoteEndPoint,
                    sslStream.IsMutuallyAuthenticated);

                serverStream = sslStream;
            }

            return new EpoxyNetworkStream(socket, serverStream, logger);
        }
开发者ID:csdahlberg,项目名称:bond,代码行数:43,代码来源:EpoxyNetworkStream.cs

示例14: HandleClient

        //This is called when requests are routed through router to this endpoint
        //For ssl requests
        private static void HandleClient(TransparentProxyEndPoint endPoint, TcpClient tcpClient)
        {
            Stream clientStream = tcpClient.GetStream();
            CustomBinaryReader clientStreamReader = null;
            StreamWriter clientStreamWriter = null;
            X509Certificate2 certificate = null;

            if (endPoint.EnableSsl)
            {
                var sslStream = new SslStream(clientStream, true);
                //if(endPoint.UseServerNameIndication)
                //{
                //   //implement in future once SNI supported by SSL stream
                //    certificate = CertManager.CreateCertificate(endPoint.GenericCertificateName);
                //}
                //else
                certificate = CertManager.CreateCertificate(endPoint.GenericCertificateName);

                try
                {
                    //Successfully managed to authenticate the client using the fake certificate
                    sslStream.AuthenticateAsServer(certificate, false,
                       SslProtocols.Tls, false);

                    clientStreamReader = new CustomBinaryReader(sslStream, Encoding.ASCII);
                    clientStreamWriter = new StreamWriter(sslStream);
                    //HTTPS server created - we can now decrypt the client's traffic

                }
                catch (Exception)
                {
                    if (sslStream != null)
                        sslStream.Dispose();

                    Dispose(tcpClient, sslStream, clientStreamReader, clientStreamWriter, null);
                    return;
                }
                clientStream = sslStream;
            }
            else
            {
                clientStreamReader = new CustomBinaryReader(clientStream, Encoding.ASCII);
            }

            var httpCmd = clientStreamReader.ReadLine();

            //Now create the request
            HandleHttpSessionRequest(tcpClient, httpCmd, clientStream, clientStreamReader, clientStreamWriter,
                true);
        }
开发者ID:aprilix,项目名称:Titanium-Web-Proxy,代码行数:52,代码来源:RequestHandler.cs

示例15: AcceptSSLCallback

 /// <summary>
 /// Accept callback method for SSL connection.
 /// </summary>
 /// <param name="ar">The socket server</param>
 private void AcceptSSLCallback(IAsyncResult ar)
 {
     AbstractSocketServer server = (AbstractSocketServer)ar.AsyncState;
     SslStream sslStream = null;
     try
     {
         // Get the socket that handles the client request.
         TcpClient sslTcpClient = server.sslListener.EndAcceptTcpClient(ar);
         Trace.WriteLine("Start incoming ssl connection ...");
         sslStream = new SslStream(sslTcpClient.GetStream(), false, new RemoteCertificateValidationCallback(server.OnVerifyClientCertificate));
         sslStream.AuthenticateAsServer(server.serverCertificate, true, SslProtocols.Ssl3, false);
         Socket handler = sslTcpClient.Client;
         handler.Blocking = true;
         AbstractTcpSocketClientHandler clientHandler = this.GetHandler(handler, sslStream);
         clientHandler.KeepAlive = this.KeepAlive;
         clientHandler.ReceiveMessageEvent += new ReceiveMessageDelegate(server.OnReceiveMessage);
         clientHandler.CloseConnectionEvent += new SocketConnectionDelegate(server.clientHandler_CloseConnectionEvent);
         server.OnConnection(clientHandler);
         server.clientList.AddClient(this.GetClientInfo(clientHandler));
         clientHandler.StartReceive();
         Trace.WriteLine("New connection completed");
     }
     catch (Exception ex)
     {
         Trace.WriteLine(string.Format("Failed to accept incoming connection. Exception", ex));
         try
         {
             if (sslStream != null)
             {
                 sslStream.Close();
                 sslStream.Dispose();
             }
         }
         catch (Exception ex2)
         {
             Trace.WriteLine(ex2);
         }
     }
     finally
     {
         // Signal the main thread to continue.
         server.listenerCompleteConnectionEvent.Set();
     }
 }
开发者ID:CuneytKukrer,项目名称:TestProject,代码行数:48,代码来源:AbstractSocketServer.cs


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