Example #1
0
        private void CompleteSendOrReceiveFirst(byte[] buffer, IAsyncResult receiveResult, IAsyncResult sendResult)
        {
            int received = 0;

            Wait(receiveResult.AsyncWaitHandle);
            while ((received = connection.EndReceive(receiveResult)) != 0)
            {
                if (received != 4)
                {
                    throw new Exception("Should be 4 bytes");
                }

                int size = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buffer, 0));
                received = 0;

                while (received != size)
                {
                    IAsyncResult r = connection.BeginReceive(buffer, received + 4, size - received, null, null);
                    Wait(r.AsyncWaitHandle);
                    received += connection.EndReceive(r);
                }
                PieceMessage   m       = (PieceMessage)PeerMessage.DecodeMessage(buffer, 0, size + 4, rig.Manager);
                RequestMessage request = (RequestMessage)requests.Messages[0];
                Assert.AreEqual(request.PieceIndex, m.PieceIndex, "#1");
                Assert.AreEqual(request.RequestLength, m.RequestLength, "#1");
                Assert.AreEqual(request.StartOffset, m.StartOffset, "#1");

                for (int i = 0; i < request.RequestLength; i++)
                {
                    if (buffer[i + 13] != (byte)(m.PieceIndex * rig.Torrent.PieceLength + m.StartOffset + i))
                    {
                        throw new Exception("Corrupted data received");
                    }
                }

                requests.Messages.RemoveAt(0);

                if (requests.Messages.Count == 0)
                {
                    //receiveResult = connection.BeginReceive(buffer, 0, 4, null, null);
                    Wait(sendResult.AsyncWaitHandle);
                    Assert.AreEqual(connection.EndSend(sendResult), amountSent);
                    break;
                }

                receiveResult = connection.BeginReceive(buffer, 0, 4, null, null);
            }

            var baseUri = new Uri(listenerURL);

            baseUri = new Uri(baseUri, rig.Manager.Torrent.Name + "/");

            if (rig.Manager.Torrent.Files.Length <= 1)
            {
                return;
            }

            Assert.AreEqual(new Uri(baseUri, rig.Manager.Torrent.Files[0].Path), _requestedUrl[0]);
            Assert.AreEqual(new Uri(baseUri, rig.Manager.Torrent.Files[1].Path), _requestedUrl[1]);
        }