EndConnect() public method

public EndConnect ( IAsyncResult asyncResult ) : void
asyncResult IAsyncResult
return void
Example #1
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;
            }
        }
Example #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;
        }
Example #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;
        }
Example #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();
        }
Example #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;
        }
Example #6
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;
        }
Example #7
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;
            }
        }
Example #8
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;
        }
Example #9
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;
			}
		}
Example #10
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;
 }
        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);
        }
Example #12
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;
 }
Example #13
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;
            }
        }
Example #14
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();
            }
        }
Example #15
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;
        }
Example #16
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);
 }
        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
        }
Example #18
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;
		}
Example #20
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");
        }
        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;
        }
Example #22
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;
        }
Example #24
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;
 }
Example #25
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;
        }
Example #26
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();
        }
 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();
     }
 }
Example #28
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();
            }
        }
Example #29
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 + ")");
        }
Example #30
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();
     }
 }