public ConnectAsyncResult(Uri uri, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state)
 {
     this.uri       = uri;
     this.addresses = SocketConnectionInitiator.GetIPAddresses(uri);
     this.port      = uri.Port;
     if (this.port == -1)
     {
         this.port = 0x328;
     }
     this.currentIndex  = 0;
     this.timeout       = timeout;
     this.timeoutHelper = new TimeoutHelper(timeout);
     if (Thread.CurrentThread.IsThreadPoolThread)
     {
         if (this.StartConnect())
         {
             base.Complete(true);
         }
     }
     else
     {
         if (startConnectCallback == null)
         {
             startConnectCallback = new Action <object>(SocketConnectionInitiator.ConnectAsyncResult.StartConnectCallback);
         }
         ActionItem.Schedule(startConnectCallback, this);
     }
 }
        public async Task <IConnection> ConnectAsync(Uri uri, TimeSpan timeout)
        {
            int port = uri.Port;

            IPAddress[] addresses = await SocketConnectionInitiator.GetIPAddressesAsync(uri);

            IConnection     socketConnection = null;
            SocketException lastException    = null;

            if (port == -1)
            {
                port = TcpUri.DefaultPort;
            }

            int           invalidAddressCount = 0;
            TimeoutHelper timeoutHelper       = new TimeoutHelper(timeout);

            for (int i = 0; i < addresses.Length; i++)
            {
                if (timeoutHelper.RemainingTime() == TimeSpan.Zero)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              CreateTimeoutException(uri, timeoutHelper.OriginalTimeout, addresses, invalidAddressCount, lastException));
                }

                DateTime connectStartTime = DateTime.UtcNow;
                try
                {
                    socketConnection = await CreateConnectionAsync(addresses[i], port);

                    lastException = null;
                    break;
                }
                catch (SocketException socketException)
                {
                    invalidAddressCount++;
                    lastException = socketException;
                }
            }

            if (socketConnection == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new EndpointNotFoundException(SR.Format(SR.NoIPEndpointsFoundForHost, uri.Host)));
            }

            if (lastException != null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          SocketConnectionInitiator.ConvertConnectException(lastException, uri,
                                                                            timeoutHelper.ElapsedTime(), lastException));
            }

            return(socketConnection);
        }
        internal override IConnectionInitiator GetConnectionInitiator()
        {
            IConnectionInitiator socketConnectionInitiator = new SocketConnectionInitiator(
                ConnectionBufferSize);

#if CONNECTIONDUMP
            socketConnectionInitiator = new ConnectionDumpInitiator(socketConnectionInitiator);
#endif
            return(new BufferedConnectionInitiator(socketConnectionInitiator,
                                                   MaxOutputDelay, ConnectionBufferSize));
        }
 private bool StartConnect()
 {
     while (this.currentIndex < this.addresses.Length)
     {
         if (this.timeoutHelper.RemainingTime() == TimeSpan.Zero)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(SocketConnectionInitiator.CreateTimeoutException(this.uri, this.timeoutHelper.OriginalTimeout, this.addresses, this.invalidAddressCount, this.lastException));
         }
         AddressFamily addressFamily = this.addresses[this.currentIndex].AddressFamily;
         if ((addressFamily == AddressFamily.InterNetworkV6) && !Socket.OSSupportsIPv6)
         {
             this.addresses[this.currentIndex++] = null;
         }
         else
         {
             this.connectStartTime = DateTime.UtcNow;
             try
             {
                 IPEndPoint remoteEP = new IPEndPoint(this.addresses[this.currentIndex], this.port);
                 this.socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
                 IAsyncResult asyncResult = this.socket.BeginConnect(remoteEP, onConnect, this);
                 if (!asyncResult.CompletedSynchronously)
                 {
                     return(false);
                 }
                 this.socket.EndConnect(asyncResult);
                 return(true);
             }
             catch (SocketException exception)
             {
                 this.invalidAddressCount++;
                 this.TraceConnectFailure(exception);
                 this.lastException = exception;
                 this.currentIndex++;
                 continue;
             }
         }
     }
     if (this.socket == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(System.ServiceModel.SR.GetString("NoIPEndpointsFoundForHost", new object[] { this.uri.Host })));
     }
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(SocketConnectionInitiator.ConvertConnectException(this.lastException, this.uri, this.timeoutHelper.ElapsedTime(), this.lastException));
 }
        public static Exception CreateRequestWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
        {
            Exception exception = ConvertWebException(webException, request, abortReason);

            if (webException.Response != null)
            {
                webException.Response.Close();
            }
            if (exception != null)
            {
                return(exception);
            }
            if (webException.InnerException is IOException)
            {
                return(CreateRequestIOException((IOException)webException.InnerException, request, webException));
            }
            if (webException.InnerException is SocketException)
            {
                return(SocketConnectionInitiator.ConvertConnectException((SocketException)webException.InnerException, request.RequestUri, TimeSpan.MaxValue, webException));
            }
            return(new EndpointNotFoundException(System.ServiceModel.SR.GetString("EndpointNotFound", new object[] { request.RequestUri.AbsoluteUri }), webException));
        }
 private void TraceConnectFailure(SocketException exception)
 {
     SocketConnectionInitiator.TraceConnectFailure(this.socket, exception, this.uri, (TimeSpan)(DateTime.UtcNow - this.connectStartTime));
     this.socket.Close();
 }