Пример #1
0
        private int ReadPacket(MemoryStream stream, out G2Packet pack)
        {
            Header h = null;
            try
            {
                h = Header.ReadHeader(stream);
            }
            catch (Exception e) {
                throw e;
            }
            int packLength = (int)(h.PayloadLength + h.HeaderLength);
            // if stream is not enough big to contain all the packet we need to read more
            if (packLength > stream.Length)
                throw new NotEnoughDataException("Not enough data in buffer");

            pack = G2PacketType.getPacketByHeader(h);
            // Set the remote host into packet for further analysis
            pack.RemotePeer = this.peer;

            // we have a unknown packet so we just read till the end of the packet
            if (pack.type == G2PacketType.DEFAULT)
            {
                // anyway, read & store the bytes
                return (int)(h.HeaderLength + pack.ReadPayload(stream, h.PayloadLength));
            }

            // we have read header, now we calculate how much byte we need to read more (children + payload)
            int byteToRead = h.PayloadLength;
            int byteRead = 0;
            bool endOfChildStream = false;

            if (h.compound)
            {

                while (true)
                {

                    G2Packet childPacket;
                    try
                    {
                        int bRead = ReadPacket(stream, out childPacket);
                        //Debug.Assert(bRead == childPacket.getTotalPacketLength(),
                            //"ReadPacket:ChildPacket " + childPacket.type + "  bRead = " + bRead + " vs " + childPacket.getTotalPacketLength());
                    }
                    catch (BigEndianPacketException e)
                    {
                        throw e;
                    }
                    catch (EndOfStreamException e)
                    {
                        byteRead += 1;
                        break;
                    }

                    pack.AddChild(childPacket);
                    byteRead += childPacket.getTotalPacketLength();
                    // root packet does NOT have a payload
                    if (byteRead == byteToRead)
                    {
                        endOfChildStream = true;
                        break;
                    }

                }
            }
            // have to count the remaining bytes, because length in header includes child packets.
            if (!endOfChildStream && (byteRead < byteToRead))
                byteRead += pack.ReadPayload(stream, byteToRead - byteRead);

            // return total read byte number
            return (int)(byteRead + h.HeaderLength);
        }