コード例 #1
0
        public bool BeginConnection()
        {
            Client = new TcpClient();
            Client.ReceiveTimeout = 1000;

            var result = Client.BeginConnect(this.IP, this.Port, null, null);

            Console.WriteLine("Connecting to: {0}:{1}", this.IP, this.Port);

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

            if (!success || !Client.Connected)
            {
                return(false);
            }

            Stream             = Client.GetStream();
            Stream.ReadTimeout = 6000;

            byte[] handshake = PacketGenerator.Handshake("BitTorrent protocol", Infohash, PeerClientID);
            Stream.Write(handshake, 0, handshake.Length);
            Stream.Flush();

#if DEBUG
            Console.WriteLine("Sent packet!");
#endif
            byte[] realRead = Read();

            if (realRead.Length < 49)
            {
#if DEBUG
                Console.WriteLine("Invalid handshake packet! Exiting!");
#endif
                Stream.Close();
                Client.Close();
                return(false);
            }

#if DEBUG
            Console.WriteLine("Received: {0} bytes", realRead.Length);
#endif
            PacketGenerator gs = new PacketGenerator(realRead);

            if (!Handshake(gs))
            {
#if DEBUG
                Console.WriteLine("Handshake failed!");
#endif
                Stream.Close();
                Client.Close();
                return(false);
            }

            Console.WriteLine("Connected!");

            State = PeerState.CHOKED;
            ChokeTimer.Reset();

            _ReadThread = new Thread(ReadThread);
            _ReadThread.Start();

            TimeManager resentTimer = new TimeManager();
            while (ThreadWorking)
            {
                if (AliveTimer.GetElapsedSeconds() > 20.0 && resentTimer.GetElapsedSeconds() > 10.0)
                {
                    resentTimer.Reset();
                    if (LastPacketSent == null)
                    {
                        Send(PacketGenerator.KeepAlive());
                    }
                    else
                    {
                        Send(LastPacketSent);
                    }
                }

                if (AliveTimer.GetElapsedSeconds() > 60.0)
                {
                    ThreadWorking = false;
                }

                Thread.Sleep(100);
            }

            ThreadWorking = false;
            return(true);
        }