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


C# TcpClient.BeginConnect方法代码示例

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


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

示例1: 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

示例2: Client

        public Client(TcpClient local, TcpClient remote, String host, int port)
        {
            _local_client   = local;
            _remote_client  = remote;

            _remote_client.BeginConnect(host, port, OnConnect, null);
        }
开发者ID:DivinityArcane,项目名称:dAmnProxy,代码行数:7,代码来源:Client.cs

示例3: Connect

        public void Connect(int localPort, int remotePort, IPAddress remoteAddress)
        {
            IPAddress localhost = Dns.GetHostAddresses("127.0.0.1")[0];
            listener = new TcpListener(localhost, localPort);
            BooleanEventArg arg;
            try
            {
                listener.Start();
            }
            catch (Exception e)
            {
                arg = new BooleanEventArg();
                arg.result = false;
                //localClientConnectedToRemoteServer.Set();
                connected(this, arg);
                return;
            }
            
            listener.BeginAcceptTcpClient(AcceptClient, listener);

            client = new TcpClient();

            Thread.Sleep(1000);
            //localClientConnectedToRemoteServer.Reset();
            client.BeginConnect(remoteAddress, remotePort, ServerConnected, client);

            //localClientConnectedToRemoteServer.WaitOne();
        }
开发者ID:Keammoort,项目名称:dotNET-lab3,代码行数:28,代码来源:Communicator.cs

示例4: Connect

        public static TcpClient Connect(string host, int port, int timeoutMSec)
        {
            TimeoutObject.Reset();
            socketexception = null;

            TcpClient tcpclient = new TcpClient();

            tcpclient.BeginConnect(host, port,
                new AsyncCallback(CallBackMethod), tcpclient);

            if (TimeoutObject.WaitOne(timeoutMSec, false))
            {
                if (IsConnectionSuccessful)
                {
                    return tcpclient;
                }
                else
                {
                    throw socketexception;
                }
            }
            else
            {
                tcpclient.Close();
                throw new TimeoutException("TimeOut Exception");
            }
        }
开发者ID:zoompf,项目名称:SPDYCheck,代码行数:27,代码来源:TimeOutSocket.cs

示例5: Start

        public static void Start()
        {
            if (run == true)
            {
                Stop();

                return;
            }

            newsysid = 1;

            listener.Start();

            listener.BeginAcceptTcpClient(DoAcceptTcpClientCallback, listener);

            foreach (var portno in portlist)
            {
                TcpClient cl = new TcpClient();

                cl.BeginConnect(IPAddress.Loopback, portno, RequestCallback, cl);

                System.Threading.Thread.Sleep(100);
            }

            th = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
            {
                IsBackground = true,
                Name = "stream combiner"
            };
            th.Start();

            MainV2.comPort.BaseStream = new TcpSerial() {client = new TcpClient("127.0.0.1", 5750) };

            MainV2.instance.doConnect(MainV2.comPort, "preset", "5750");
        }
开发者ID:ArduPilot,项目名称:MissionPlanner,代码行数:35,代码来源:StreamCombiner.cs

示例6: CheckMinecraft

        public void CheckMinecraft()
        {
            if (!NeedToUpdate("minecraft", 30))
                return;

            TcpClient tcp = new TcpClient();
            try
            {
                tcp.SendTimeout = 2000;
                tcp.ReceiveTimeout = 2000;
                tcp.NoDelay = true;
                tcp.Client.ReceiveTimeout = 2000;
                tcp.Client.SendTimeout = 2000;

                var async = tcp.BeginConnect(MinecraftHost, MinecraftPort, null, null);
                DateTime dt = DateTime.Now;
                while ((DateTime.Now - dt).TotalSeconds < 3 && !async.IsCompleted)
                    System.Threading.Thread.Sleep(40);
                if (!async.IsCompleted)
                {
                    try
                    {
                        tcp.Close();
                    }
                    catch { { } }
                    MinecraftOnline = false;
                    return;
                }

                if (!tcp.Connected)
                {
                    log.Fatal("Minecraft server is offline.");
                    MinecraftOnline = false;
                    return;
                }

                var ns = tcp.GetStream();
                var sw = new StreamWriter(ns);
                var sr = new StreamReader(ns);

                ns.WriteByte(0xFE);

                if (ns.ReadByte() != 0xFF)
                    throw new Exception("Invalid data");

                short strlen = BitConverter.ToInt16(ns.ReadBytes(2), 0);
                string strtxt = Encoding.BigEndianUnicode.GetString(ns.ReadBytes(2 * strlen));

                string[] strdat = strtxt.Split('§'); // Description§Players§Slots[§]
                MinecraftOnline = true;
                MinecraftSvrDescription = strdat[0];
                MinecraftCurPlayers = ulong.Parse(strdat[1]);
                MinecraftMaxPlayers = ulong.Parse(strdat[2]);
            }
            catch (Exception n)
            {
                log.Fatal("Minecraft server check error: " + n);
                MinecraftOnline = false;
            }
        }
开发者ID:bobolo,项目名称:fourdeltaone-status,代码行数:60,代码来源:SSMinecraftCheck.cs

示例7: ConnValidate

        public static bool ConnValidate(String host, int port, int timeoutMSec)
        {
            bool ret = false;
            timeoutObject.Reset();
            socketException = null;

            TcpClient tcpClient = new TcpClient();
            tcpClient.BeginConnect(host, port, new AsyncCallback(CallBackMethod), tcpClient);

            if (timeoutObject.WaitOne(timeoutMSec, false))
            {
                if (IsConnectionSuccessful)
                {
                    ret = true;
                    tcpClient.Close();
                }
                else
                {
                    //throw socketException;
                }
            }
            else
            {
                //throw new TimeoutException();
            }
            tcpClient.Close();

            return ret;
        }
开发者ID:g992com,项目名称:esb,代码行数:29,代码来源:NetPortON.cs

示例8: 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

示例9: startCommLaser

        private void startCommLaser()
        {
            int remotePort = 10002;

            String IPAddr = jaguarSetting.LaserRangeIP;
            firstSetupComm = true;
            try
            {
                //clientSocket = new TcpClient(IPAddr, remotePort);
                clientSocketLaser = new TcpClient();
                IAsyncResult results = clientSocketLaser.BeginConnect(IPAddr, remotePort, null, null);
                bool success = results.AsyncWaitHandle.WaitOne(500, true);
                
                if (!success)
                {
                    clientSocketLaser.Close();
                    clientSocketLaser = null;
                    receivingLaser = false;
                    pictureBoxLaser.Image = imageList1.Images[3];
                }
                else
                {
                    receivingLaser = true;
                    threadClientLaser = new Thread(new ThreadStart(HandleClientLaser));
                    threadClientLaser.CurrentCulture = new CultureInfo("en-US");
                    threadClientLaser.Start();
                    pictureBoxLaser.Image = imageList1.Images[2];
                }
            }
            catch
            {
                pictureBoxLaser.Image = imageList1.Images[3];

            }
        }
开发者ID:vaibhavviswanathan,项目名称:E160,代码行数:35,代码来源:LaserScan.cs

示例10: 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

示例11: 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

示例12: Connect

        public static TcpClient Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
        {
            TimeoutObject.Reset();
            socketexception = null;

            string serverip = Convert.ToString(remoteEndPoint.Address);
            int serverport = remoteEndPoint.Port;
            TcpClient tcpclient = new TcpClient();

            tcpclient.BeginConnect(serverip, serverport,
                new AsyncCallback(CallBackMethod), tcpclient);

            if (TimeoutObject.WaitOne(timeoutMSec, false))
            {
                if (IsConnectionSuccessful)
                {
                    return tcpclient;
                }
                else
                {
                    throw socketexception;
                }
            }
            else
            {
                tcpclient.Close();
                throw new TimeoutException("TimeOut Exception");
            }
        }
开发者ID:Wolfury,项目名称:MTConnect4OPC,代码行数:29,代码来源:TimeoutSocket.cs

示例13: Start

        public static void Start()
        {
            if (run == true)
            {
                Stop();
                
                return;
            }

            newsysid = 1;

            listener.Start();

            listener.BeginAcceptTcpClient(DoAcceptTcpClientCallback, listener);

            foreach (var portno in portlist)
            {
                TcpClient cl = new TcpClient();

                cl.BeginConnect(IPAddress.Loopback, portno, RequestCallback, cl);

                System.Threading.Thread.Sleep(500);
            }

            th = new System.Threading.Thread(new System.Threading.ThreadStart(mainloop))
            {
                IsBackground = true,
                Name = "stream combiner"
            };
            th.Start();
        }
开发者ID:jackmaynard,项目名称:MissionPlanner,代码行数:31,代码来源:StreamCombiner.cs

示例14: Connect

        public void Connect()
        {
            if (_client != null) return;
            
            try
            {
                ReadyState = ReadyStates.CONNECTING;

                _client = new TcpClient();
                _connecting = true;
                _client.BeginConnect(_host, _port, OnRunClient, null);

                var waiting = new TimeSpan();
                while (_connecting && waiting < ConnectTimeout)
                {
                    var timeSpan = new TimeSpan(0, 0, 0, 0, 100);
                    waiting = waiting.Add(timeSpan);
                    Thread.Sleep(timeSpan.Milliseconds);
                }
                if (_connecting) throw new Exception("Timeout");
            }
            catch (Exception)
            {
                Disconnect();
                OnFailedConnection(null);
            }
        }
开发者ID:vegazrelli,项目名称:GazeTracker2.0,代码行数:27,代码来源:WebSocketClient.cs

示例15: 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


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