EndConnect() публичный Метод

public EndConnect ( IAsyncResult asyncResult ) : void
asyncResult IAsyncResult
Результат void
Пример #1
0
        /// <summary>
        /// Methode callback appelée lorsque la connexion est effective.
        /// </summary>
        /// <param name="result"></param>
        private void OnConnect(IAsyncResult result)
        {
            try
            {
                _tcpClient.EndConnect(result);

                _connected = true;

                NetworkStream stream = _tcpClient.GetStream();
                if (stream != null)
                {
                    stream.BeginRead(_buffer, 0, _buffer.Length, OnDataReceived, this);

                    if (this.ReferenceDelegate != null)
                    {
                        this.ReferenceDelegate.OnConnect(this);
                    }
                }
            }
            catch (Exception e)
            {
                if (this.ReferenceDelegate != null)
                {
                    this.ReferenceDelegate.OnError(e, this);
                }
            }
        }
Пример #2
0
        //This method uses TCPClient to check the validity of the domain name and returns true if domain exists, and false if it doesn't
        private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
        {
            System.Uri uri = new Uri(aDomain);
            string uriWithoutScheme = uri.Host.TrimEnd('/');
            try
            {
                using (TcpClient client = new TcpClient())
                {
                    var result = client.BeginConnect(uriWithoutScheme, 80, null, null);

                    var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));

                    if (!success)
                    {
                       // Console.Write(aDomain + " ---- No such domain exists\n");
                        return false;
                    }

                    // we have connected
                    client.EndConnect(result);
                    return true;
                }
            }
            catch (Exception ex)
            {
               // Console.Write(aDomain + " ---- " + ex.Message + "\n");
            }
            return false;
        }
Пример #3
0
        public void Connect()
        {
            try
            {
                Close();
            }
            catch (Exception) { }
            client = new TcpClient();
            client.NoDelay = true;
            IAsyncResult ar = client.BeginConnect(Host, Port, null, null);
            System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                {
                    client.Close();
                    throw new IOException("Connection timoeut.", new TimeoutException());
                }

                client.EndConnect(ar);
            }
            finally
            {
                wh.Close();
            }
            stream = client.GetStream();
            stream.ReadTimeout = 10000;
            stream.WriteTimeout = 10000;
        }
Пример #4
0
        /// <summary>
        /// Begins the connection process to the server, including the sending of a handshake once connected.
        /// </summary>
        public void Connect()
        {
            try {
                BaseSock = new TcpClient();
                var ar = BaseSock.BeginConnect(ClientBot.Ip, ClientBot.Port, null, null);

                using (ar.AsyncWaitHandle) {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false)) {
                        BaseSock.Close();
                        ClientBot.RaiseErrorMessage("Failed to connect: Timeout.");
                        return;
                    }

                    BaseSock.EndConnect(ar);
                }
            } catch (Exception e) {
                ClientBot.RaiseErrorMessage("Failed to connect: " + e.Message);
                return;
            }

            ClientBot.RaiseInfoMessage("Connected to server.");

            BaseStream = BaseSock.GetStream();
            WSock = new ClassicWrapped.ClassicWrapped {_Stream = BaseStream};

            DoHandshake();

            _handler = new Thread(Handle);
            _handler.Start();

            _timeoutHandler = new Thread(Timeout);
            _timeoutHandler.Start();
        }
Пример #5
0
        private static bool IsPortOpen(IPAddress ipAddress, int currentPort, int connectTimeout)
        {
            bool portIsOpen = false;

            using (var tcp = new TcpClient())
            {
                IAsyncResult ar = tcp.BeginConnect(ipAddress, currentPort, null, null);
                using (ar.AsyncWaitHandle)
                {
                    //Wait connectTimeout ms for connection.
                    if (ar.AsyncWaitHandle.WaitOne(connectTimeout, false))
                    {
                        try
                        {
                            tcp.EndConnect(ar);
                            portIsOpen = true;
                            //Connect was successful.
                        }
                        catch
                        {
                            //Server refused the connection.
                        }
                    }
                }
            }

            return portIsOpen;
        }
Пример #6
0
    public static bool IsPortOpen(string host, int port, int timeout = 2000, int retry = 1)
    {
        var retryCount = 0;

        while (retryCount < retry)
        {
            // Logical delay without blocking the current thread.
            if (retryCount > 0)
            {
                System.Threading.Tasks.Task.Delay(timeout).Wait();
            }
            var client = new System.Net.Sockets.TcpClient();
            try
            {
                var result  = client.BeginConnect(host, port, null, null);
                var success = result.AsyncWaitHandle.WaitOne(timeout);
                if (success)
                {
                    client.EndConnect(result);
                    return(true);
                }
            }
            catch
            {
                // ignored
            }
            finally
            {
                client.Close();
                retryCount++;
            }
        }
        return(false);
    }
Пример #7
0
        public Boolean Connect(IPAddress hostAddr, Int32 hostPort, Int32 timeout)
        {
            // Create new instance of TCP client
            _Client = new TcpClient();
            var result = _Client.BeginConnect(hostAddr, hostPort, null, null);

            _TransmitThread = null;

            result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout));
            if (!_Client.Connected)
            {
                return false;
            }

            // We have connected
            _Client.EndConnect(result);
            EventHandler handler = OnConnected;
            if(handler != null)
            {
                handler(this, EventArgs.Empty);
            }

            // Now we are connected --> start async read operation.
            NetworkStream networkStream = _Client.GetStream();
            byte[] buffer = new byte[_Client.ReceiveBufferSize];
            networkStream.BeginRead(buffer, 0, buffer.Length, OnDataReceivedHandler, buffer);

            // Start thread to manage transmission of messages
            _TransmitThreadEnd = false;
            _TransmitThread = new Thread(TransmitThread);
            _TransmitThread.Start();

            return true;
        }
Пример #8
0
        public SensorState DoCheckState(Server target)
        {
            try
            {
                using (TcpClient client = new TcpClient())
                {

                    var result = client.BeginConnect(target.FullyQualifiedHostName, Port, null, null);
                    var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2));

                    if (!success)
                        return SensorState.Error;

                    client.EndConnect(result);
                }
                return SensorState.OK;
            }
            catch (SocketException)
            {
                //TODO: Check for Status
                return SensorState.Error;
            }
            catch (Exception)
            {
                return SensorState.Error;
            }
        }
Пример #9
0
        public static bool Ping(string host, int port, TimeSpan timeout, out TimeSpan elapsed)
        {
            using (TcpClient tcp = new TcpClient())
            {
                DateTime start = DateTime.Now;
                IAsyncResult result = tcp.BeginConnect(host, port, null, null);
                WaitHandle wait = result.AsyncWaitHandle;
                bool ok = true;

                try
                {
                    if (!result.AsyncWaitHandle.WaitOne(timeout, false))
                    {
                        tcp.Close();
                        ok = false;
                    }

                    tcp.EndConnect(result);
                }
                catch
                {
                    ok = false;
                }
                finally
                {
                    wait.Close();
                }

                DateTime stop = DateTime.Now;
                elapsed = stop.Subtract(start);
                return ok;
            }
        }
Пример #10
0
        public bool Connect(string ip, int port)
        {
            try
            {
                Disconnect();

                AutoResetEvent autoResetEvent = new AutoResetEvent(false);

                tcpClient = new TcpClient();

                tcpClient.BeginConnect(ip,
                                       port,
                                       new AsyncCallback(
                                           delegate(IAsyncResult asyncResult)
                                           {
                                               try
                                               {
                                                   tcpClient.EndConnect(asyncResult);
                                               }
                                               catch { }

                                               autoResetEvent.Set();
                                           }
                                       ),
                                       tcpClient);

                if (!autoResetEvent.WaitOne())
                    throw new Exception();

                networkStream = tcpClient.GetStream();

                thread = new Thread(new ThreadStart(Read));

                thread.IsBackground = true;
                thread.Name = "ReadThread";
                thread.Start();

                return true;
            }
            catch (Exception e)
            {
                ICtrl.logger.Info("Connect(...) exception:");

                ICtrl.logger.Info("ip: " + ip);
                ICtrl.logger.Info("port: " + port);

                ICtrl.logger.Info(e.Message);
                ICtrl.logger.Info(e.Source);
                ICtrl.logger.Info(e.StackTrace);

                DBConnection.Instance.Disconnect();

                Environment.Exit(0);
            }

            return false;
        }
Пример #11
0
		public bool Send(string hostName, int port = 80, bool throwOnError = true, int timeout = 100)
		{
			try
			{
				using (var tcpClient = new TcpClient())
				{
					var asyncResult = tcpClient.BeginConnect(hostName, port, null, null);
					var asyncWaitHandle = asyncResult.AsyncWaitHandle;

					try
					{
						if (!asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false))
						{
							tcpClient.Close();

							if (throwOnError)
							{
								throw new TimeoutException();
							}

							return false;
						}

						try
						{
							tcpClient.EndConnect(asyncResult);
						}
						catch
						{
							if (throwOnError)
							{
								throw;
							}

							return false;
						}

						return true;
					}
					finally
					{
						asyncWaitHandle.Close();
					}
				}
			}
			catch
			{
				if (throwOnError)
				{
					throw;
				}

				return false;
			}
		}
Пример #12
0
 /// <summary>
 /// Checks, if a certain <paramref name="port"/> is opened on a given <paramref name="host"/>.
 /// </summary>
 /// <param name="host">IP-Address or host name to check for the port.</param>
 /// <param name="port">The port-number to check.</param>
 /// <param name="timeout">The timeout in seconds to wait for a reply.</param>
 /// <param name="useUdp"><c>true</c> if a UDP port should be checked.</param>
 /// <returns><c>True</c> if the port is opened, otherwise <c>false.</c></returns>
 public static bool IsPortOpened(string host, int port, int timeout = 1, bool useUdp = false)
 {
     var result = false;
     if (!useUdp)
     {
         // Use TCP
         var client = new TcpClient();
         try
         {
             client.ReceiveTimeout = timeout * 1000;
             client.SendTimeout = timeout * 1000;
             var asyncResult = client.BeginConnect(host, port, null, null);
             var waitHandle = asyncResult.AsyncWaitHandle;
             try
             {
                 if (asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false))
                 {
                     // The result was positiv
                     result = client.Connected;
                 }
                 // ensure the ending-call
                 client.EndConnect(asyncResult);
             }
             finally
             {
                 // Ensure to close the wait handle.
                 waitHandle.Close();
             }
         }
         catch { }
         finally
         {
             // wait handle didn't came back in time
             client.Close();
         }
     }
     else
     {
         // Use UDP
         var client = new UdpClient();
         try
         {                    
             client.Connect(host, port);
             result = true;                    
         }
         catch { }
         finally
         {
             // wait handle didn't came back in time
             client.Close();
         }
     }            
     return result;
 }
Пример #13
0
 private void ConnectResult(IAsyncResult ar)
 {
     System.Net.Sockets.TcpClient socket = (System.Net.Sockets.TcpClient)ar.AsyncState;
     if (socket.Client != null && socket.Connected)
     {
         socket.EndConnect(ar);
         NetworkStream stream = socket.GetStream();
         stream.BeginRead(recvBuffer, 0, recvBuffer.Length, ReadResult, socket);
         Debug.Log("客户端连接成功!");
         MsgManager.Instance.Enqueue(MsgID.ConnectSuccess, "客户端连接成功");
     }
 }
Пример #14
0
        public static ISocket Open(IPAddress address, int port, TimeSpan connectTimeout) {
            var timeout = new ManualResetEvent(false);
            Exception connectFailure = null;
            var tcpClient = new TcpClient();
            var ar = tcpClient.BeginConnect(address, port, r => {
                try {
                    tcpClient.EndConnect(r);
                } catch(Exception e) {
                    connectFailure = e;
                } finally {
                    timeout.Set();
                }
            }, null);

            if(!timeout.WaitOne(connectTimeout)) {
                tcpClient.EndConnect(ar);
                throw new TimeoutException();
            }
            if(connectFailure != null) {
                throw new ConnectException(connectFailure);
            }
            return new SocketAdapter(tcpClient);
        }
Пример #15
0
 public static Future<TcpClient> ConnectTo (string host, int port) {
     var f = new Future<TcpClient>();
     TcpClient client = new TcpClient();
     client.BeginConnect(host, port, (ar) => {
         try {
             client.EndConnect(ar);
             f.Complete(client);
         } catch (FutureHandlerException) {
             throw;
         } catch (Exception ex) {
             f.Fail(ex);
             client.Close();
         }
     }, null);
     return f;
 }
Пример #16
0
        public void CheckAvailable(int timeout)
        {
            TcpClient FClient = new TcpClient();
            var result = FClient.BeginConnect(Server, Port, null, null);

            bool success = result.AsyncWaitHandle.WaitOne(timeout, true);
            if (success)
            {
                FClient.EndConnect(result);
                FClient.Close();
                Available = true;
            }
            else
            {
                FClient.Close();
                Available = false;
            }
        }
Пример #17
0
        //public bool ConnectLocking(string host, int port)
        //{
        //    using (var tcp = new TcpClient())
        //    {
        //        //add time out here?
        //        tcp.Connect(host, port);

        //        return tcp.Connected;
        //    }

        //}

        public bool ConnectAPM(string host, int port)
        {
            using (var tcp = new TcpClient())
            {
                var ar = tcp.BeginConnect(host, port, null, null);
                using (ar.AsyncWaitHandle)
                {
                    //Wait 2 seconds for connection.
                    if (ar.AsyncWaitHandle.WaitOne(500, false))
                    {
                        tcp.EndConnect(ar);
                        return true;
                        //Connect was successful.

                    }
                }
            }
            return false;
        }
Пример #18
0
        private static void ConnectTcpSocket(TcpClient client, string hostName, int port, TimeSpan timeout)
        {
            var ar = client.BeginConnect(hostName, port, null, null);
            var wh = ar.AsyncWaitHandle;
            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(timeout, false))
                {
                    client.Close();
                    throw new TimeoutException();
                }

                client.EndConnect(ar);
            }
            finally
            {
                wh.Close();
            }
        }
        public static void TestUntilConnectionMade(string IPAdress, int port)
        {
            var client = new TcpClient();

            while (!client.Connected)
            {
                var result = client.BeginConnect(IPAdress, port, null, null);

                result.AsyncWaitHandle.WaitOne(500);
                if (!client.Connected)
                {
                    Console.WriteLine("Failed to connect.");
                    Thread.Sleep(5000);
                    continue;
                }
                client.EndConnect(result);

            }
            // we have connected
        }
 private void ConnectResult(IAsyncResult ar)
 {
     socket = (System.Net.Sockets.TcpClient)ar.AsyncState;
     if (socket.Client != null && socket.Connected)
     {
         socket.EndConnect(ar);
         NetworkStream stream = socket.GetStream();
         stream.BeginRead(recvBuffer, 0, recvBuffer.Length, ReadResult, socket);
         Debug.Log("客户端连接成功!");
         IsConnected = true;
         MsgManager.Instance.Dispatch(MsgID.ConnectSuccess, null);
     }
     else
     {
         Debug.LogError("客户端连接失败!");
         IsConnected = false;
         MsgManager.Instance.Dispatch(MsgID.ConnectFailed, null);
     }
     IsConnecting = false;
 }
Пример #21
0
 public static IConnector ConnectSSL(string host, int port, Factory factory, object contextFactory, int timeout, string bindAddress)
 {
     TcpClient client = new TcpClient();
     IAsyncResult ar = client.BeginConnect(host, port, null, null);
     WaitHandle wh = ar.AsyncWaitHandle;
     try
     {
         if (!wh.WaitOne(TimeSpan.FromMilliseconds(timeout), false))
         {
             client.Close();
             throw new TimeoutException();
         }
         client.EndConnect(ar);
     }
     finally
     {
         wh.Close();
     }
     return new SSLConnector(client, factory);
 }
Пример #22
0
        private bool SendDTO(ResultDTO dto)
        {
            if (m_LostConnection) return false;
#if UTT_SOCKETS_SUPPORTED 
            try
            {
                using (var tcpClient = new TcpClient())
                {
                    var result = tcpClient.BeginConnect(m_Ip, m_Port, null, null);
                    var success = result.AsyncWaitHandle.WaitOne(m_ConnectionTimeout);
                    if (!success)
                    {
                        return false;
                    }
                    try
                    {
                        tcpClient.EndConnect(result);
                    }
                    catch (SocketException)
                    {
                        m_LostConnection = true;
                        return false;
                    }

                    var bf = new DTOFormatter();
                    bf.Serialize(tcpClient.GetStream(), dto);
                    tcpClient.GetStream().Close();
                    tcpClient.Close();
                    Debug.Log("Sent " + dto.messageType);
                }
            }
            catch (SocketException e)
            {
                Debug.LogException(e);
                m_LostConnection = true;
                return false;
            }
#endif  // if UTT_SOCKETS_SUPPORTED
            return true;
        }
		private bool SendDTO(ResultDTO dto)
		{
			if (lostConnection) return false;
#if !UNITY_METRO
			try
			{
				using (var tcpClient = new TcpClient())
				{
					var result = tcpClient.BeginConnect (ip, port, null, null);
					var success = result.AsyncWaitHandle.WaitOne(ConnectionTimeout);
					if (!success)
					{
						return false;
					}
					try
					{
						tcpClient.EndConnect (result);
					}
					catch (SocketException)
					{
						lostConnection = true;
						return false;
					}

					var bf = new BinaryFormatter();
					bf.Serialize(tcpClient.GetStream(), dto);
					tcpClient.GetStream().Close ();
					tcpClient.Close();
					UnityEngine.Debug.Log ("Sent " + dto.messageType);
				}
			}
			catch (SocketException e)
			{
				UnityEngine.Debug.LogException (e);
				lostConnection = true;
				return false;
			}
#endif
			return true;
		}
Пример #24
0
        /// <summary>
        /// Starts the network handler. (Connects to a minecraft server)
        /// </summary>
        public void Start() {
            try {
                _baseSock = new TcpClient();
                var ar = _baseSock.BeginConnect(_mainMc.ServerIp, _mainMc.ServerPort, null, null);

                using (var wh = ar.AsyncWaitHandle) {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false)) {
                        _baseSock.Close();
                        RaiseSocketError(this, "Failed to connect: Connection Timeout");
                        return;
                    }

                    _baseSock.EndConnect(ar);
                }

            } catch (Exception e) {
                RaiseSocketError(this, "Failed to connect: " + e.Message);
                return;
            }
            
            _mainMc.Running = true;

            RaiseSocketInfo(this, "Connected to server.");
            RaiseSocketDebug(this, string.Format("IP: {0} Port: {1}", _mainMc.ServerIp, _mainMc.ServerPort.ToString()));

            // -- Create our Wrapped socket.
            _baseStream = _baseSock.GetStream();
            WSock = new Wrapped(_baseStream);
            RaiseSocketDebug(this, "Socket Created");

            DoHandshake();

            _packetHandlers = new PacketEventHandler(this);

            // -- Start network parsing.
            _handler = new Thread(NetworkPacketHandler);
            _handler.Start();
            RaiseSocketDebug(this, "Handler thread started");
        }
Пример #25
0
        void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                lock (tcpClient)
                    tcpClient.EndConnect(ar);

                BeginReceive();

                Status = TcpClientStatus.Connected;
                connectEvent.Set();

                if (OnConnect != null)
                {
                    OnConnect(this);
                }
            }
            catch (SocketException ex)
            {
                OnErrorInternal(ex);
            }
        }
        public static bool IsPortOpen(string host, int port, int timeout)
        {
            try
            {
                using (var client = new TcpClient())
                {
                    var result = client.BeginConnect(host, port, null, null);
                    var success = result.AsyncWaitHandle.WaitOne(timeout);
                    if (!success)
                    {
                        return false;
                    }

                    client.EndConnect(result);
                }

            }
            catch
            {
                return false;
            }
            return true;
        }
Пример #27
0
        private static void CallBackMethod(IAsyncResult asyncresult)
        {
            try
            {
                IsConnected = false;
                TCP.TcpClient tcpclient = asyncresult.AsyncState as TCP.TcpClient;

                if (tcpclient.Client != null)
                {
                    tcpclient.EndConnect(asyncresult);
                    IsConnected = true;
                }
            }
            catch (Exception ex)
            {
                IsConnected     = false;
                socketexception = ex;
            }
            finally
            {
                tcpConnector.Set();
            }
        }
Пример #28
0
        private static TcpClient Connect(string host)
        {
            var timeoutObject = new ManualResetEvent(false);
            var connected = false;
            Exception exception = null;
            var client = new TcpClient();
            client.BeginConnect(host, 23, ar =>
                {
                    try
                    {
                        connected = false;
                        if (client.Client != null)
                        {
                            client.EndConnect(ar);
                            connected = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        connected = false;
                        exception = ex;
                    }
                    finally
                    {
                        timeoutObject.Set();
                    }
                }, null);

            if (timeoutObject.WaitOne(5000, false))
            {
                if (connected) return client;
                throw new TelnetException(host, exception.Message);
            }

            client.Close();
            throw new TelnetException(host, "The connection timed out.");
        }
        protected override TcpClient connectSpecific()
        {
            TcpClient client = null;
            client = new TcpClient();
            IAsyncResult result = client.BeginConnect(System.Net.IPAddress.Parse(hostIP), Global.WIFI_PORT, null, null);
            do
            {
                System.Diagnostics.Debug.WriteLine("TCPClient connecting with: " + hostIP);
                System.Threading.Thread.Sleep(200);
            } while (!result.IsCompleted && isAlive);

            if (!isAlive)
                client = null;
            else
            {
                try { client.EndConnect(result); }
                catch (SocketException) {
                    client = null;
                    connectionTimeout = true;
                }
            }

            return client;
        }
Пример #30
0
 public bool Connect(string address, int port)
 {
     _client = new TcpClient();
     IAsyncResult result = _client.BeginConnect(address, port, null, null);
     WaitHandle timeoutHandler = result.AsyncWaitHandle;
     try
     {
         if (!result.AsyncWaitHandle.WaitOne(2000, false))
         {
             _client.Close();
             return false;
         }
         _client.EndConnect(result);
     }
     catch (Exception)
     {
         return false;
     }
     finally
     {
         timeoutHandler.Close();
     }
     return true;
 }
 private void Connect(TcpClient socket, AmqpTcpEndpoint endpoint, int timeout)
 {
     IAsyncResult ar = null;
     try
     {
         ar = socket.BeginConnect(endpoint.HostName, endpoint.Port, null, null);
         if (!ar.AsyncWaitHandle.WaitOne(timeout, false))
         {
             socket.Close();
             throw new TimeoutException("Connection to " + endpoint + " timed out");
         }
         socket.EndConnect(ar);
     }
     catch (ArgumentException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     catch (SocketException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     finally
     {
         if (ar != null)
             ar.AsyncWaitHandle.Close();
     }
 }
Пример #32
0
        /// <summary>
        /// Establish a connection to the server.
        /// </summary>
        public void Connect()
        {
            if (IsConnected)
            {
                Logger?.Invoke(_Header + "already connected");
                return;
            }
            else
            {
                Logger?.Invoke(_Header + "initializing client");

                InitializeClient(_Ssl, _PfxCertFilename, _PfxPassword);

                Logger?.Invoke(_Header + "connecting to " + ServerIpPort);
            }

            _TokenSource = new CancellationTokenSource();
            _Token       = _TokenSource.Token;

            IAsyncResult ar = _Client.BeginConnect(_ServerIp, _ServerPort, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(_Settings.ConnectTimeoutMs), false))
                {
                    _Client.Close();
                    throw new TimeoutException("Timeout connecting to " + ServerIpPort);
                }

                _Client.EndConnect(ar);
                _NetworkStream = _Client.GetStream();

                if (_Ssl)
                {
                    if (_Settings.AcceptInvalidCertificates)
                    {
                        _SslStream = new SslStream(_NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        _SslStream = new SslStream(_NetworkStream, false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertCollection, SslProtocols.Tls12, !_Settings.AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }
                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }
                    if (_Settings.MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }
                }

                if (_Keepalive.EnableTcpKeepAlives)
                {
                    EnableKeepalives();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                wh.Close();
            }

            _IsConnected  = true;
            _LastActivity = DateTime.Now;
            _IsTimeout    = false;
            _Events.HandleConnected(this, new ClientConnectedEventArgs(ServerIpPort));
            _DataReceiver      = Task.Run(() => DataReceiver(_Token), _Token);
            _IdleServerMonitor = Task.Run(() => IdleServerMonitor(), _Token);
        }
Пример #33
0
        /// <summary>
        /// Establish the connection to the server.
        /// </summary>
        /// <param name="RemoteIP">The server IP address.</param>
        /// <param name="Port">The TCP port on which to connect.</param>
        /// <param name="ConnectionTimeout">The timeout for this operation in milliseonds</param>
        public void Connect(IPAddress RemoteIP, int Port, int ConnectionTimeout = 5000)
        {
            Logger.Log(Logger.Level.Info, "Attempting connection to the remote socket");

            try
            {
                if (Port < 0)
                {
                    throw new ArgumentException("Negative values not supported.", nameof(Port));
                }
                if (ConnectionTimeout < 0)
                {
                    throw new ArgumentException("ConnectionTimeout must be zero or greater.", nameof(ConnectionTimeout));
                }

                this.RemoteIP = RemoteIP ?? throw new ArgumentNullException("Null values are not supported", nameof(RemoteIP));
                this.Port     = Port;

                TokenSource = new CancellationTokenSource();
                Client      = new System.Net.Sockets.TcpClient();

                Logger.Log(Logger.Level.Debug, $"Timeout: {ConnectionTimeout}");
                Logger.Log(Logger.Level.Debug, "Beginning socket connection");

                var ar = Client.BeginConnect(RemoteIP, Port, null, null);

                try
                {
                    if (!ar.AsyncWaitHandle.WaitOne(ConnectionTimeout, false))
                    {
                        Client.Close();
                        throw new TimeoutException($"Timeout connecting to {this.RemoteIP}:{this.Port}");
                    }

                    Client.EndConnect(ar);

                    Logger.Log(Logger.Level.Info, "Connection to remote socket succeeded");

                    NetworkStream = Client.GetStream();
                    Connected     = true;
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    ar.AsyncWaitHandle.Close();
                }

                Logger.Log(Logger.Level.Info, $"Raising the {nameof(ConnectedEvent)} event");

                var args = new object[] { this, EventArgs.Empty };
                ConnectedEvent.RaiseEventSafe(ref args);

                Logger.Log(Logger.Level.Info, $"Starting socket monitoring");

                DataReceiverLoop = Task.Run(() => DataReceiver(Token), Token);
            }
            catch (Exception ex)
            {
                Logger.Log(Logger.Level.Error, $"Failed to connect to the remote socket.\n\n{ex.Message}");
                throw;
            }
        }
Пример #34
0
 /// <summary>
 /// 数据Socket连接服务器的回调函数
 /// </summary>
 /// <param name="asy"></param>
 public void connect_callBack(IAsyncResult asy)
 {
     #if DEBUG
     OESClient.logForm.InsertMsg("In [DataPort.connect_callBack]");
     #endif
     dataTrans = (TcpClient)asy.AsyncState;
     dataTrans.EndConnect(asy);
     data_ns = dataTrans.GetStream();
     if (ConnectedDataPort != null)
     {
         ConnectedDataPort(this, null);
     }
     if (IsSend)
     {
         SendData();
     }
     else
     {
         ReceiveData();
     }
 }
Пример #35
0
        /// <summary>
        /// Establish the connection to the server.
        /// </summary>
        public void Connect()
        {
            IAsyncResult ar = _TcpClient.BeginConnect(_ServerIp, _Port, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(_ConnectTimeoutSeconds), false))
                {
                    _TcpClient.Close();
                    throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _Port);
                }

                _TcpClient.EndConnect(ar);
                _NetworkStream = _TcpClient.GetStream();

                if (_Ssl)
                {
                    if (AcceptInvalidCertificates)
                    {
                        // accept invalid certs
                        _SslStream = new SslStream(_NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        // do not accept invalid SSL certificates
                        _SslStream = new SslStream(_NetworkStream, false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertCollection, SslProtocols.Tls12, !AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }

                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }

                    if (MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }
                }

                _Connected = true;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                wh.Close();
            }

            if (Connected != null)
            {
                Task.Run(() => Connected());
            }

            Task.Run(() => DataReceiver(_Token), _Token);
        }
Пример #36
0
        internal void IdentificaComunicacaoAplicacaoLocalRemota()
        {
            try
            {
                CaseBusiness.Framework.BancoDados.Entidade.Configuracao conf         = null;
                CaseBusiness.Framework.BancoDados.Processo.Configuracao confProcesso = new CaseBusiness.Framework.BancoDados.Processo.Configuracao();
                conf = confProcesso.BuscarStringConexao(CaseBusiness.Framework.Configuracao.Configuracao.BancoPrincipal);
                Boolean conexaoViaIP = true;

                if (conf != null)
                {
                    IPAddress ipAddr   = null;
                    String    ipOuNome = "";
                    String    host     = "";
                    String[]  pIP      = null;
                    Int32     ipOut    = Int32.MinValue;
                    Byte[]    ip       = new Byte[4];

                    if (conf.Servidor.IndexOf(@"\") > -1)
                    {
                        ipOuNome = conf.Servidor.Remove(conf.Servidor.IndexOf(@"\")).Replace(".", "");
                    }
                    else
                    {
                        ipOuNome = conf.Servidor.Replace(".", "");
                    }

                    if (Int32.TryParse(ipOuNome, out ipOut))
                    {
                        if (conf.Servidor.IndexOf(@"\") > -1)
                        {
                            pIP = conf.Servidor.Remove(conf.Servidor.IndexOf(@"\")).Split('.');
                        }
                        else
                        {
                            pIP = conf.Servidor.Split('.');
                        }

                        ip[0] = Convert.ToByte(pIP[0]);
                        ip[1] = Convert.ToByte(pIP[1]);
                        ip[2] = Convert.ToByte(pIP[2]);
                        ip[3] = Convert.ToByte(pIP[3]);

                        ipAddr = new IPAddress(ip);

                        conexaoViaIP = true;
                    }
                    else
                    {
                        conexaoViaIP = false;

                        if (conf.Servidor.IndexOf(@"\") > -1)
                        {
                            host = conf.Servidor.Remove(conf.Servidor.IndexOf(@"\"));
                        }
                        else
                        {
                            host = conf.Servidor;
                        }
                    }

                    using (System.Net.Sockets.TcpClient tcpSocket = new System.Net.Sockets.TcpClient())
                    {
                        IAsyncResult async = null;

                        if (conexaoViaIP)
                        {
                            async = tcpSocket.BeginConnect(ipAddr, Convert.ToInt32(conf.Porta), new AsyncCallback(Result), null);
                        }
                        else
                        {
                            async = tcpSocket.BeginConnect(host, Convert.ToInt32(conf.Porta), new AsyncCallback(Result), null);
                        }

                        DateTime startTime = DateTime.Now;

                        do
                        {
                            System.Threading.Thread.Sleep(500);

                            if (async.IsCompleted)
                            {
                                break;
                            }
                        }while (DateTime.Now.Subtract(startTime).TotalSeconds < 5);

                        if (async.IsCompleted)
                        {
                            tcpSocket.EndConnect(async);
                            CaseBusiness.Framework.Configuracao.Configuracao._tipoComunicacao = TipoComunicacao.Local;
                        }

                        tcpSocket.Close();

                        if (!async.IsCompleted)
                        {
                            //DataSet ds = null;

                            //CaseWSFramework.FrameworkSoapClient fWS = new CaseWSFramework.FrameworkSoapClient();

                            //CaseWSFramework.App app = CaseWSFramework.App.CaseManagerCliente;
                            //ds = fWS.BuscarConfiguracao(app);

                            //CaseBusiness.Framework.Configuracao.Configuracao._tipoComunicacao = TipoComunicacao.Remota;
                        }
                    }
                }
            }
            catch (SocketException)
            {
                //DataSet ds = null;

                //CaseWSFramework.FrameworkSoapClient fWS = new CaseWSFramework.FrameworkSoapClient();

                //CaseWSFramework.App app = CaseWSFramework.App.CaseManagerCliente;
                //ds = fWS.BuscarConfiguracao(app);

                //CaseBusiness.Framework.Configuracao.Configuracao._tipoComunicacao = TipoComunicacao.Remota;
            }
            catch (System.Exception ex)
            {
                CaseBusiness.Framework.Configuracao.Configuracao._erroInicializacao = "Erro: " + ex.Message;
                CaseBusiness.Framework.Log.Log.LogarArquivo("Erro: " + ex.Message + " " + ex.StackTrace, CaseBusiness.Framework.Log.TipoEventoLog.Erro, "Case Framework");

                if (ex.InnerException != null)
                {
                    CaseBusiness.Framework.Log.Log.LogarArquivo("Erro: " + ex.InnerException.ToString() + " " + ex.StackTrace, CaseBusiness.Framework.Log.TipoEventoLog.Erro, "Case Framework");
                }
                throw;
            }
        }
Пример #37
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length == 2)
                {
                    int    port = 0;
                    string host = args[0];
                    try
                    {
                        port = Convert.ToInt32(args[1]);
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("Could not parse port number.");
                        Console.WriteLine("");
                        Environment.Exit(2);
                    }

                    System.Net.Sockets.TcpClient tcpclient = new System.Net.Sockets.TcpClient();
                    IAsyncResult connection = tcpclient.BeginConnect(host, port, null, null);
                    System.Threading.WaitHandle waithandle = connection.AsyncWaitHandle;
                    tcpclient.SendTimeout = 3000;

                    try
                    {
                        if (!connection.AsyncWaitHandle.WaitOne(tcpclient.SendTimeout, false))
                        {
                            tcpclient.Close();
                            throw new TimeoutException();
                        }

                        tcpclient.EndConnect(connection);
                        Console.WriteLine("");
                        Console.WriteLine("Successfully connected to server.");
                        Console.WriteLine("");
                        Environment.Exit(1);
                    }
                    catch (TimeoutException)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("The connection attempt timed out.");
                        Console.WriteLine("");
                        Environment.Exit(2);
                    }
                    catch (SocketException)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("Connection actively refused.");
                        Console.WriteLine("");
                    }
                    finally
                    {
                        waithandle.Close();
                    }
                }
                else
                {
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                Console.WriteLine("");
                Console.WriteLine("Invalid arguments");
                Console.WriteLine("");
                Environment.Exit(2);
            }
        }
Пример #38
0
        void connect()
        {
            client = new TcpClient();

            //Notify we are connecting
            var eoc = this.OnConnecting;
            if (eoc != null)
                eoc(this.appleSettings.Host, this.appleSettings.Port);

            try
            {
                var connectDone = new AutoResetEvent(false);

                //Connect async so we can utilize a connection timeout
                connectAsyncResult = client.BeginConnect(
                    appleSettings.Host, appleSettings.Port,
                    new AsyncCallback(
                        delegate(IAsyncResult ar)
                        {
                            if (connectAsyncResult != ar)
                                return;

                            try
                            {
                                client.EndConnect(ar);

                                //Set keep alive on the socket may help maintain our APNS connection
                                //client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                                //Really not sure if this will work on MONO....
                                try { client.SetSocketKeepAliveValues(20 * 60 * 1000, 30 * 1000); }
                                catch { }

                                Interlocked.Increment(ref reconnects);

                                //Trigger the reset event so we can continue execution below
                                connectDone.Set();
                            }
                            catch (Exception ex)
                            {
                                Log.Error("APNS Connect Callback Failed: " + ex);
                            }
                        }
                    ), client
                );

                if (!connectDone.WaitOne(appleSettings.ConnectionTimeout))
                {
                    throw new TimeoutException("Connection to Host Timed Out!");
                }
            }
            catch (Exception ex)
            {
                throw new ConnectionFailureException("Connection to Host Failed", ex);
            }

            if (appleSettings.SkipSsl)
            {
                networkStream = client.GetStream();
            }
            else
            {
                RemoteCertificateValidationCallback userCertificateValidation;

                if (appleSettings != null && appleSettings.ValidateServerCertificate)
                {
                    userCertificateValidation = ValidateRemoteCertificate;
                }
                else
                {
                    userCertificateValidation = (sender, cert, chain, sslPolicyErrors) => true; //Don't validate remote cert
                }

                stream = new SslStream(client.GetStream(), false,
                    userCertificateValidation,
                    (sender, targetHost, localCerts, remoteCert, acceptableIssuers) => certificate);

                try
                {
                    stream.AuthenticateAsClient(this.appleSettings.Host, this.certificates, System.Security.Authentication.SslProtocols.Ssl3, false);
                    //stream.AuthenticateAsClient(this.appleSettings.Host);
                }
                catch (System.Security.Authentication.AuthenticationException ex)
                {
                    throw new ConnectionFailureException("SSL Stream Failed to Authenticate as Client", ex);
                }

                if (!stream.IsMutuallyAuthenticated)
                    throw new ConnectionFailureException("SSL Stream Failed to Authenticate", null);

                if (!stream.CanWrite)
                    throw new ConnectionFailureException("SSL Stream is not Writable", null);

                networkStream = stream;
            }

            //Start reading from the stream asynchronously
            Reader();
        }
Пример #39
0
        public void Connect(Uri address)
        {
            IPAddress ip;

            if (address.HostNameType == UriHostNameType.Dns)
                ip = LookupDNS(address.Host);
            else
                ip = IPAddress.Parse(address.Host);

            if (ip == null)
                throw new HttpFetchException("No DNS for " + address.Host);

            //TODO: loop for all dns ips on connect failures

            var tcp = new TcpClient();
            var result = tcp.BeginConnect(ip, address.Port, null, null);
            if (!result.AsyncWaitHandle.WaitOne(ConnectTimeout, true))
            {
                tcp.Close();
                throw new HttpFetchException("Timeout connecting to " + ip);
            }
            tcp.EndConnect(result);
            socket = tcp.Client;
            stream = tcp.GetStream();

            if (address.Scheme == "https")
            {
                //Broken in mono with newer ciphers
                /*
                var ssl = new SslStream(stream, false, VerifyCert);
                ssl.AuthenticateAsClient(address.Host);
                stream = ssl;*/

                var handler = new TlsClientProtocol(stream, new SecureRandom());
                handler.Connect(new MyTlsClient(address.Host));
                stream = handler.Stream;
            }

            reader = new StreamLineReader(stream);
            Console.WriteLine("Connected to " + socket.RemoteEndPoint + "(" + address.Host + ")");
        }
Пример #40
0
        private IEnumerator<int> SendInternal(AsyncEnumerator ae)
        {
            try
            {
                using (var client = new TcpClient())
                {
                    try
                    {
                        client.BeginConnect(Destination.Host, Destination.Port,
                                            ae.End(),
                                            null);
                    }
                    catch (Exception exception)
                    {
                        logger.WarnFormat("Failed to connect to {0} because {1}", Destination, exception);
                        Failure(exception);
                        yield break;
                    }

                    yield return 1;

                    try
                    {
                        client.EndConnect(ae.DequeueAsyncResult());
                    }
                    catch (Exception exception)
                    {
                        logger.WarnFormat("Failed to connect to {0} because {1}", Destination, exception);
                        Failure(exception);
                        yield break;
                    }

                    logger.DebugFormat("Successfully connected to {0}", Destination);

                    using (var stream = client.GetStream())
                    {
                        var buffer = Messages.Serialize();

                        var bufferLenInBytes = BitConverter.GetBytes(buffer.Length);

                        logger.DebugFormat("Writing length of {0} bytes to {1}", buffer.Length, Destination);

                        try
                        {
                            stream.BeginWrite(bufferLenInBytes, 0, bufferLenInBytes.Length, ae.End(), null);
                        }
                        catch (Exception exception)
                        {
                            logger.WarnFormat("Could not write to {0} because {1}", Destination,
                                              exception);
                            Failure(exception);
                            yield break;
                        }

                        yield return 1;

                        try
                        {
                            stream.EndWrite(ae.DequeueAsyncResult());
                        }
                        catch (Exception exception)
                        {
                            logger.WarnFormat("Could not write to {0} because {1}", Destination,
                                              exception);
                            Failure(exception);
                            yield break;
                        }

                        logger.DebugFormat("Writing {0} bytes to {1}", buffer.Length, Destination);

                        try
                        {
                            stream.BeginWrite(buffer, 0, buffer.Length, ae.End(), null);
                        }
                        catch (Exception exception)
                        {
                            logger.WarnFormat("Could not write to {0} because {1}", Destination,
                                            exception);
                            Failure(exception);
                            yield break;
                        }

                        yield return 1;

                        try
                        {
                            stream.EndWrite(ae.DequeueAsyncResult());
                        }
                        catch (Exception exception)
                        {
                            logger.WarnFormat("Could not write to {0} because {1}", Destination,
                                              exception);
                            Failure(exception);
                            yield break;
                        }

                        logger.DebugFormat("Successfully wrote to {0}", Destination);

                        var recieveBuffer = new byte[ProtocolConstants.RecievedBuffer.Length];
                        var readConfirmationEnumerator = new AsyncEnumerator();

                        try
                        {
                            readConfirmationEnumerator.BeginExecute(
                                StreamUtil.ReadBytes(recieveBuffer, stream, readConfirmationEnumerator, "recieve confirmation", false), ae.End());
                        }
                        catch (Exception exception)
                        {
                            logger.WarnFormat("Could not read confirmation from {0} because {1}", Destination,
                                              exception);
                            Failure(exception);
                            yield break;
                        }

                        yield return 1;

                        try
                        {
                            readConfirmationEnumerator.EndExecute(ae.DequeueAsyncResult());
                        }
                        catch (Exception exception)
                        {
                            logger.WarnFormat("Could not read confirmation from {0} because {1}", Destination,
                                              exception);
                            Failure(exception);
                            yield break;
                        }

                        var recieveRespone = Encoding.Unicode.GetString(recieveBuffer);
                        if (recieveRespone == ProtocolConstants.QueueDoesNotExists)
                        {
                            logger.WarnFormat(
                                "Response from reciever {0} is that queue does not exists",
                                Destination);
                            Failure(new QueueDoesNotExistsException());
                            yield break;
                        }
                        else if(recieveRespone!=ProtocolConstants.Recieved)
                        {
                            logger.WarnFormat(
                                "Response from reciever {0} is not the expected one, unexpected response was: {1}",
                                Destination, recieveRespone);
                            Failure(null);
                            yield break;
                        }

                        try
                        {
                            stream.BeginWrite(ProtocolConstants.AcknowledgedBuffer, 0,
                                              ProtocolConstants.AcknowledgedBuffer.Length, ae.End(), null);
                        }
                        catch (Exception exception)
                        {
                            logger.WarnFormat("Failed to write acknowledgement to reciever {0} because {1}",
                                              Destination, exception);
                            Failure(exception);
                            yield break;
                        }

                        yield return 1;

                        try
                        {
                            stream.EndWrite(ae.DequeueAsyncResult());
                        }
                        catch (Exception exception)
                        {
                            logger.WarnFormat("Failed to write acknowledgement to reciever {0} because {1}",
                                              Destination, exception);
                            Failure(exception);
                            yield break;
                        }

                        var bookmarks = Success();

                        buffer = new byte[ProtocolConstants.RevertBuffer.Length];
                        var readRevertMessage = new AsyncEnumerator(ae.ToString());
                        bool startingToReadFailed = false;
                        try
                        {
                            readRevertMessage.BeginExecute(
                                StreamUtil.ReadBytes(buffer, stream, readRevertMessage, "revert", true), ae.End());
                        }
                        catch (Exception)
                        {
                            //more or less expected
                            startingToReadFailed = true;
                        }
                        if (startingToReadFailed)
                            yield break;
                        yield return 1;
                        try
                        {
                            readRevertMessage.EndExecute(ae.DequeueAsyncResult());
                            var revert = Encoding.Unicode.GetString(buffer);
                            if (revert == ProtocolConstants.Revert)
                            {
                                logger.Warn("Got back revert message from receiver, reverting send");
                                Revert(bookmarks);
                            }
                        }
                        catch (Exception)
                        {
                            // expected, there is nothing to do here, the
                            // reciever didn't report anything for us
                        }

                    }
                }
            }
            finally
            {
                var completed = SendCompleted;
                if (completed != null)
                    completed();
            }
        }
Пример #41
0
        private TcpClient CreateTcpConnection(string host, int port)
        {
            TcpClient tcpClient;

            if (_currentProxy == null)
            {
                #region Создание подключения

                tcpClient = new TcpClient();

                Exception connectException = null;
                var connectDoneEvent = new ManualResetEventSlim();

                try
                {
                    tcpClient.BeginConnect(host, port, new AsyncCallback(
                        (ar) =>
                        {
                            try
                            {
                                tcpClient.EndConnect(ar);
                            }
                            catch (Exception ex)
                            {
                                connectException = ex;
                            }

                            connectDoneEvent.Set();
                        }), tcpClient
                    );
                }
                #region Catch's

                catch (Exception ex)
                {
                    tcpClient.Close();

                    if (ex is SocketException || ex is SecurityException)
                    {
                        throw NewHttpException(Resources.HttpException_FailedConnect, ex, HttpExceptionStatus.ConnectFailure);
                    }

                    throw;
                }

                #endregion

                if (!connectDoneEvent.Wait(_connectTimeout))
                {
                    tcpClient.Close();
                    throw NewHttpException(Resources.HttpException_ConnectTimeout, null, HttpExceptionStatus.ConnectFailure);
                }

                if (connectException != null)
                {
                    tcpClient.Close();

                    if (connectException is SocketException)
                    {
                        throw NewHttpException(Resources.HttpException_FailedConnect, connectException, HttpExceptionStatus.ConnectFailure);
                    }

                    throw connectException;
                }

                if (!tcpClient.Connected)
                {
                    tcpClient.Close();
                    throw NewHttpException(Resources.HttpException_FailedConnect, null, HttpExceptionStatus.ConnectFailure);
                }

                #endregion

                tcpClient.SendTimeout = _readWriteTimeout;
                tcpClient.ReceiveTimeout = _readWriteTimeout;
            }
            else
            {
                try
                {
                    tcpClient = _currentProxy.CreateConnection(host, port);
                }
                catch (ProxyException ex)
                {
                    throw NewHttpException(Resources.HttpException_FailedConnect, ex, HttpExceptionStatus.ConnectFailure);
                }
            }

            return tcpClient;
        }
Пример #42
0
        /// <summary>
        /// Establish the connection to the server.
        /// </summary>
        public void Connect(int timeoutSeconds)
        {
            if (timeoutSeconds < 1)
            {
                throw new ArgumentException("TimeoutSeconds must be greater than zero seconds.");
            }

            IAsyncResult ar = _TcpClient.BeginConnect(_ServerIp, _ServerPort, null, null);
            WaitHandle   wh = ar.AsyncWaitHandle;

            try
            {
                if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeoutSeconds), false))
                {
                    _TcpClient.Close();
                    throw new TimeoutException("Timeout connecting to " + _ServerIp + ":" + _ServerPort);
                }

                _TcpClient.EndConnect(ar);
                _NetworkStream = _TcpClient.GetStream();

                if (_Ssl)
                {
                    if (AcceptInvalidCertificates)
                    {
                        // accept invalid certs
                        _SslStream = new SslStream(_NetworkStream, false, new RemoteCertificateValidationCallback(AcceptCertificate));
                    }
                    else
                    {
                        // do not accept invalid SSL certificates
                        _SslStream = new SslStream(_NetworkStream, false);
                    }

                    _SslStream.AuthenticateAsClient(_ServerIp, _SslCertCollection, SslProtocols.Tls12, !AcceptInvalidCertificates);

                    if (!_SslStream.IsEncrypted)
                    {
                        throw new AuthenticationException("Stream is not encrypted");
                    }

                    if (!_SslStream.IsAuthenticated)
                    {
                        throw new AuthenticationException("Stream is not authenticated");
                    }

                    if (MutuallyAuthenticate && !_SslStream.IsMutuallyAuthenticated)
                    {
                        throw new AuthenticationException("Mutual authentication failed");
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                wh.Close();
            }

            Stats = new Statistics();
            Logger?.Invoke("Starting connection monitor for: " + _ServerIp + ":" + _ServerPort);
            Task unawaited = Task.Run(() => ClientConnectionMonitor());

            ClientConnected?.Invoke(this, EventArgs.Empty);

            _IsConnected = true;
        }