46 lines
1.5 KiB
C#
46 lines
1.5 KiB
C#
using PSO2SERVER.Models;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
|
||
namespace PSO2SERVER.Protocol
|
||
{
|
||
public abstract class Packet
|
||
{
|
||
public abstract byte[] Build();
|
||
public abstract PacketHeader GetHeader();
|
||
|
||
// 新增:获取整体数据包字节表示
|
||
public byte[] GetPacketBytes()
|
||
{
|
||
var header = GetHeader(); // 获取包头
|
||
var packetBody = Build(); // 获取包体
|
||
|
||
// 如果包头的大小为0,则重新计算
|
||
if (header.Size == 0)
|
||
{
|
||
// 包头(包括固定的前四个字节)的大小加上包体的大小
|
||
header.Size = (uint)(header.ToBytes().Length + packetBody.Length);
|
||
}
|
||
|
||
// 将包头与包体合并
|
||
var totalPacket = new List<byte>();
|
||
totalPacket.AddRange(header.ToBytes()); // 包头转换为字节并加入
|
||
totalPacket.AddRange(packetBody); // 包体加入
|
||
|
||
return totalPacket.ToArray(); // 返回整个数据包字节数组
|
||
}
|
||
}
|
||
|
||
public class PacketError : Exception
|
||
{
|
||
public string PacketName { get; }
|
||
public string FieldName { get; }
|
||
|
||
public PacketError(string packetName, string fieldName, Exception innerException)
|
||
: base($"Error in packet '{packetName}', field '{fieldName}'", innerException)
|
||
{
|
||
PacketName = packetName;
|
||
FieldName = fieldName;
|
||
}
|
||
}
|
||
} |