Пример #1
0
        protected virtual P2PTcpClient TryRadomPort(string ip, int port)
        {
            P2PTcpClient  ret    = null;
            AsyncCallback action = ar =>
            {
                P2PTcpClient tcp = ar.AsyncState as P2PTcpClient;
                EasyOp.Do(() => tcp.EndConnect(ar), () =>
                {
                    if (tcp != null && tcp.Connected)
                    {
                        ret = tcp;
                    }
                }, ex =>
                {
                    LogUtils.Trace($"{ex.Message}");
                });
            };
            List <P2PTcpClient> tcpList = new List <P2PTcpClient>();

            for (int i = 1; i <= 8; i++)
            {
                P2PTcpClient tcp = new P2PTcpClient();
                tcpList.Add(tcp);
                tcp.BeginConnect(ip, port + 6, action, tcp);
            }
            int cTime = 0;

            while (ret == null && cTime < 3000)
            {
                Thread.Sleep(100);
                cTime += 100;
            }
            tcpList.ForEach(t =>
            {
                if (t != ret)
                {
                    EasyOp.Do(() => t.Close());
                    EasyOp.Do(() => t.Dispose());
                }
            });
            return(ret);
        }