packet structure
This commit is contained in:
42
MySolution/STcpHelper/Packet/STcpPacketHeader.cs
Normal file
42
MySolution/STcpHelper/Packet/STcpPacketHeader.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace STcpHelper.Packet
|
||||
{
|
||||
/// <summary>
|
||||
/// 4byte header
|
||||
/// </summary>
|
||||
public class STcpPacketHeader : ISTcpPacket
|
||||
{
|
||||
public PacketType Type { get; private set; }
|
||||
public short DataLength { get; private set; }
|
||||
|
||||
public STcpPacketHeader(PacketType type, int dataLength)
|
||||
{
|
||||
Type = type;
|
||||
DataLength = (short)dataLength;
|
||||
}
|
||||
|
||||
public STcpPacketHeader(byte[] buffer)
|
||||
{
|
||||
int cursor = 0;
|
||||
this.Type = (PacketType)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, cursor));
|
||||
cursor += 2;
|
||||
|
||||
this.DataLength = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, cursor));
|
||||
}
|
||||
|
||||
// [2bytes Type][2bytes Size]
|
||||
public byte[] Serialize()
|
||||
{
|
||||
byte[] type = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)this.Type));
|
||||
byte[] size = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(this.DataLength));
|
||||
|
||||
return SBufferHelper.GetBuffer(type.Length + size.Length, type, size);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user