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


C# TcpClient.EndConnect方法代码示例

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


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

示例1: Ping

        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;
            }
        }
开发者ID:blake2002,项目名称:gNetSockets,代码行数:33,代码来源:NetUtility.cs

示例2: IsDomainAlive

        //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;
        }
开发者ID:adityanag,项目名称:webcrawl,代码行数:30,代码来源:Crawler.cs

示例3: Connect

        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;
        }
开发者ID:dantarion,项目名称:tcp-gecko-dotnet,代码行数:29,代码来源:tcpconn.cs

示例4: Connect

        /// <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();
        }
开发者ID:umby24,项目名称:ClassicBot,代码行数:36,代码来源:NetworkManager.cs

示例5: IsPortOpen

        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;
        }
开发者ID:RomanySaad,项目名称:MultiMiner,代码行数:28,代码来源:PortScanner.cs

示例6: Connect

        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;
        }
开发者ID:vannivinti,项目名称:SVS-Emulator,代码行数:34,代码来源:TcpClient.cs

示例7: DoCheckState

        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;
            }
        }
开发者ID:mriedmann,项目名称:oom,代码行数:27,代码来源:TcpPortSensor.cs

示例8: Connect

        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;
        }
开发者ID:sokolnikov90,项目名称:ICTRL,代码行数:57,代码来源:IPConnection.cs

示例9: Send

		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;
			}
		}
开发者ID:matteomigliore,项目名称:HSDK,代码行数:55,代码来源:NetTcpPing.cs

示例10: IsPortOpened

 /// <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;
 }
开发者ID:codingfreak,项目名称:cfUtils,代码行数:62,代码来源:NetworkUtil.cs

示例11: Open

        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);
        }
开发者ID:hurricane2,项目名称:libBeanstalk.NET,代码行数:23,代码来源:SocketAdapter.cs

示例12: ConnectTo

 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;
 }
开发者ID:mbahar94,项目名称:fracture,代码行数:16,代码来源:Network.cs

示例13: CheckAvailable

        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;
            }
        }
开发者ID:TNOCS,项目名称:csTouch,代码行数:18,代码来源:ImbConnectionString.cs

示例14: ConnectTcpSocket

        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();
            }
        }
开发者ID:tleviathan,项目名称:redfoxmq,代码行数:19,代码来源:SocketFactory.cs

示例15: ConnectAPM

        //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;
        }
开发者ID:d6-9b,项目名称:CodeTests,代码行数:31,代码来源:TestClass.cs


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