first commit
This commit is contained in:
53
MMOTestServer/ServerLib/Packet/PacketSerializer.cs
Normal file
53
MMOTestServer/ServerLib/Packet/PacketSerializer.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using ProtoBuf;
|
||||
using Serilog;
|
||||
|
||||
namespace ServerLib.Packet
|
||||
{
|
||||
// 패킷 헤더 크기 4(패킷 타입, 패킷 길이)
|
||||
|
||||
public static class PacketSerializer
|
||||
{
|
||||
// 직렬화: 객체 → byte[]
|
||||
public static byte[] Serialize<T>(ushort type, ushort size, T packet)
|
||||
{
|
||||
MemoryStream ms = new MemoryStream();
|
||||
|
||||
// 2바이트 패킷 타입 헤더
|
||||
ms.WriteByte((byte)(type & 0xFF));
|
||||
ms.WriteByte((byte)(type >> 8));
|
||||
|
||||
// 2바이트 패킷 길이 헤더
|
||||
ms.WriteByte((byte)(size & 0xFF));
|
||||
ms.WriteByte((byte)(size >> 8));
|
||||
|
||||
// protobuf 페이로드
|
||||
Serializer.Serialize(ms, packet);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
// 역직렬화: byte[] → (PacketType, payload bytes)
|
||||
public static (ushort type, ushort size, byte[] payload) Deserialize(byte[] data)
|
||||
{
|
||||
if (data.Length < 4)
|
||||
{
|
||||
Log.Warning("[PacketHeader]의 길이가 4이하입니다.");
|
||||
return (0, 0, null)!;
|
||||
}
|
||||
|
||||
// 길이체크도 필요함
|
||||
|
||||
ushort type = (ushort)(data[0] | (data[1] << 8));
|
||||
ushort size = (ushort)(data[2] | (data[3] << 8));
|
||||
byte[] payload = new byte[data.Length - 4];
|
||||
Buffer.BlockCopy(data, 4, payload, 0, payload.Length);
|
||||
return (type, size, payload);
|
||||
}
|
||||
|
||||
// 페이로드 → 특정 타입으로 역직렬화
|
||||
public static T DeserializePayload<T>(byte[] payload)
|
||||
{
|
||||
MemoryStream ms = new MemoryStream(payload);
|
||||
return Serializer.Deserialize<T>(ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user