Beispiel #1
0
        /// <summary>
        /// If necessary, connect the remote <c>SocketPS</c> socket
        /// to the given host and port
        /// </summary>
        /// <param name="hostname">Remote host name</param>
        /// <param name="port">Remote port</param>
        /// <remarks>
        /// If SocketPS is already connected to the right host and port,
        /// the socket is reused as is.
        /// </remarks>
        protected void Connect(string hostname, int port, bool secure)
        {
            System.Diagnostics.Debug.Assert(!String.IsNullOrEmpty(hostname));
            System.Diagnostics.Debug.Assert(port > 0);

            if (DestinationHostName != null &&
                DestinationHostName.Equals(hostname) &&
                DestinationPort == port &&
                (SocketPS != null && !SocketPS.IsSocketDead()))
            {
                // Nothing to do, just reuse the socket
                return;
            }

            if (SocketPS != null)
            {
                log.Debug("Changing hostname/port from " +
                          DestinationHostName + ":" + DestinationPort +
                          " to " + hostname + ":" + port);

                // We have a socket connected to the wrong host (or port)
                SocketPS.CloseSocket();
                SocketPS = null;
            }

            IPAddress[] ips    = Resolve(hostname);
            Socket      socket = null;
            Exception   e      = null;

            foreach (var ip in ips)
            {
                try
                {
                    socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                    socket.Connect(ip, port);
                    break;
                }
                catch (Exception ee)
                {
                    if (ip.Equals(IPAddress.IPv6Loopback))
                    {
                        // Do not log that
                        continue;
                    }

                    if (e == null)
                    {
                        e = ee;
                    }
                    if (socket != null)
                    {
                        socket.Close();
                        socket = null;
                    }

                    log.Error(ee);
                }
            }
            if (socket == null)
            {
                throw e;
            }

            // Checked up, and good to go
            SocketPS = new HttpSocket(socket);
            if (secure)
            {
                SocketPS.MakeSecureClient(hostname);
            }
            DestinationHostName = hostname;
            DestinationPort     = port;

            log.Debug("SocketPS connected to " + hostname + ":" + port);
        }