示例#1
0
        public byte[] HandlePacket(byte[] array)
        {
            // Push the bytes into a new databuffer object.
            var  packet  = new DataBuffer(array);
            bool process = true;

            // Continue to loop while there's still data to process.
            while (process)
            {
                // Get the size of the next packet.
                int size = packet.ReadInt();

                // Do we have more than all the data needed for the packet?
                if (array.Length > size)
                {
                    // Resize the array containing the bytes needed for this packet, and
                    // create a new array containing the excess.
                    byte[] excessbuffer = new byte[array.Length - size];
                    Array.ConstrainedCopy(array, size, excessbuffer, 0, array.Length - size);
                    Array.Resize(ref array, size);

                    // Read the packet head, validate its contents, and invoke its data handler.
                    int head = packet.ReadInt();
                    if (PacketHandlers.ContainsKey(head))
                    {
                        PacketHandlers[head].Invoke(RemovePacketHead(array));
                    }

                    // Re-create the databuffer object with just the excess bytes, and
                    // continue to loop.
                    packet = new DataBuffer(excessbuffer);

                    // Do we have all the data needed for the packet?
                }
                else if (array.Length == size)
                {
                    // Read the packet head, validate its contents, and invoke its data handler.
                    int head = packet.ReadInt();
                    if (PacketHandlers.ContainsKey(head))
                    {
                        PacketHandlers[head].Invoke(RemovePacketHead(array));
                    }

                    // Return an empty array.
                    return(new byte[0]);
                }
                else
                {
                    // Display a message if something goes wrong.
                    if (size > 8192)
                    {
                        MyFiles.Write("Absurd packet size expected: " + size);
                        return(new byte[0]);
                    }

                    // We have less data than we need. There's nothing to process yet.
                    process = false;
                }
            }

            // Return the unprocessed bytes.
            return(packet.ToArray());
        }