[Serializable]
public abstract class PacketBase {
protected PacketHead packetHead;
protected PacketPayload packetPayload;
public PacketBase(PacketHead packetHead, PacketPayload packetPayload) {
this.packetHead = packetHead;
this.packetPayload = packetPayload;
if(packetPayload != null) {
this.packetHead.PayloadLength = packetPayload.RawData.Length;
}
}
public PacketBase() {
this.packetHead = new PacketHead();
this.packetPayload = new PacketPayload();
}
/// <summary>
/// 与Packet对应的二进制数据报
/// </summary>
public byte[] ByteArray {
get {
byte[] buf = null;
if(packetPayload != null) {
buf = new byte[packetHead.RawData.Length + packetPayload.RawData.Length];
Array.Copy(packetHead.RawData, buf, packetHead.RawData.Length);
Array.Copy(packetPayload.RawData, 0, buf, packetHead.RawData.Length, packetPayload.RawData.Length);
} else {
buf = new byte[packetHead.RawData.Length];
Array.Copy(packetHead.RawData, buf, packetHead.RawData.Length);
}
return buf;
}
set {
if(value.Length >= PacketHead.HeadLength) {
byte[] buf = new byte[PacketHead.HeadLength];
Array.Copy(value, buf, PacketHead.HeadLength);
packetHead = new PacketHead(buf);
int nPayload = value.Length - PacketHead.HeadLength;
if(nPayload > 0) {
buf = new byte[nPayload];
Array.Copy(value, PacketHead.HeadLength, buf, 0, nPayload);
packetPayload = new PacketPayload(buf);
} else {
packetPayload = null;
}
} else {
throw new Exception(Properties.Resources.DataLengthError);
}
}
}
#region 公开Packet头部的属性
public PacketType PacketType {
get {
return packetHead.PacketType;
}
}
public IPAddress SourceIp {
get {
return packetHead.SourceIp;
}
set {
packetHead.SourceIp = value;
}
}
public IPAddress DestIp {
get {
return packetHead.DestIp;
}
set {
packetHead.DestIp = value;
}
}
public int PktId {
get {
return packetHead.PktId;
}
set {
packetHead.PktId = value;
}
}
public int PayloadLength {
get {
return packetHead.PayloadLength;
}
set {
packetHead.PayloadLength = value;
}
}
#endregion
}