JD2022-TU1/main/tools/framework/JD.Remoting/Details/PacketHeader.cs

88 lines
No EOL
2.5 KiB
C#

using System.IO;
using System.Linq;
using System.Text;
using JD.Remoting.Exceptions;
namespace JD.Remoting.Details
{
/// <summary>
/// The header data of a packet.
/// </summary>
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";
/// <summary>
/// Body size of all packets (including the message header).
/// </summary>
public uint GlobalBodySize;
/// <summary>
/// Body size of the current packet.
/// </summary>
public uint BodySize;
/// <summary>
/// Index of the packet in the current message packets.
/// </summary>
public uint Index;
/// <summary>
/// Index of the last packet of the message.
/// </summary>
public uint MaxIndex;
/// <summary>
/// Global id of the message (all the packets of the same message wear the same id).
/// </summary>
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);
}
}
}