using System.IO; using System.Linq; using System.Text; using JD.Remoting.Exceptions; namespace JD.Remoting.Details { /// /// The header data of a packet. /// internal class PacketHeader { private static uint _counter = 1; private static readonly byte[] _headerInBytes = Encoding.ASCII.GetBytes(PacketHeaderTag + "\0000"); public const int HeaderSize = 36; public const string PacketHeaderTag = "IFT_TCP_HEAD"; /// /// Body size of all packets (including the message header). /// public uint GlobalBodySize; /// /// Body size of the current packet. /// public uint BodySize; /// /// Index of the packet in the current message packets. /// public uint Index; /// /// Index of the last packet of the message. /// public uint MaxIndex; /// /// Global id of the message (all the packets of the same message wear the same id). /// public uint MessageId; public static uint NextMessageId { get { unchecked { return _counter++; } } } public void Read(Stream stream) { var reader = new BinaryReader(stream); var header = reader.ReadBytes(16); if (!header.Take(PacketHeaderTag.Length).SequenceEqual(_headerInBytes.Take(PacketHeaderTag.Length))) // Only the ITFPart { throw new RemotingInvalidDataException("Message header is invalid or not initialized. "); } GlobalBodySize = reader.ReadUInt32(); BodySize = reader.ReadUInt32(); Index = reader.ReadUInt32(); MaxIndex = reader.ReadUInt32(); MessageId = reader.ReadUInt32(); if (MessageId == 0) { throw new RemotingInvalidDataException("Message header is invalid or not initialized. "); } } public void Write(Stream stream) { var writer = new BinaryWriter(stream); writer.Write(_headerInBytes); writer.Write(GlobalBodySize); writer.Write(BodySize); writer.Write(Index); writer.Write(MaxIndex); writer.Write(MessageId); } } }