10 Commits

22 changed files with 1073 additions and 355 deletions

View File

@@ -0,0 +1,135 @@
using LiteNetLib;
using Serilog;
namespace ClientTester.DummyService;
public class DummyClientService
{
private readonly List<DummyClients> clients;
private readonly int sendInterval;
// 모든거 강종
public event Action? OnAllDisconnected;
public DummyClientService(int count, string ip, int port, string key, int sendIntervalMs = 1000, MapBounds? mapBounds = null)
{
sendInterval = sendIntervalMs;
clients = Enumerable.Range(1, count).Select(i =>
{
DummyClients client = new DummyClients(i, ip, port, key);
if (mapBounds != null)
{
client.Map = mapBounds;
}
return client;
}).ToList();
Log.Information("[SERVICE] {Count}개 클라이언트 생성 → {Ip}:{Port}", count, ip, port);
}
public async Task RunAsync(CancellationToken ct)
{
await Task.WhenAll(PollLoopAsync(ct), SendLoopAsync(ct));
}
private async Task PollLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
foreach (DummyClients c in clients)
{
try
{
c.PollEvents();
}
catch (Exception ex)
{
Log.Error("[Client {ClientId}] PollEvents 예외: {Ex}", c.clientId, ex.Message);
}
}
await Task.Delay(10);
}
}
private async Task SendLoopAsync(CancellationToken ct)
{
await Task.Delay(500);
int tick = 0;
while (!ct.IsCancellationRequested)
{
int sent = 0;
int total = clients.Count;
foreach (DummyClients client in clients)
{
client.SendTransform();
if (client.peer != null)
{
sent++;
}
else
{
total--;
}
}
if (total == 0)
{
Log.Information("All Disconnect Clients");
OnAllDisconnected?.Invoke();
break;
}
Log.Debug("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total);
tick++;
await Task.Delay(sendInterval);
}
}
public void PrintStats()
{
int totalSent = 0, totalRecv = 0;
int connected = 0;
Log.Information("───────────── Performance Report ─────────────");
foreach (DummyClients c in clients)
{
NetStatistics? stats = c.peer?.Statistics;
long loss = stats?.PacketLoss ?? 0;
float lossPct = stats?.PacketLossPercent ?? 0f;
Log.Information(
"[Client {ClientId:00}] Sent={Sent} Recv={Recv} | Loss={Loss}({LossPct:F1}%)",
c.clientId, c.SentCount, c.ReceivedCount, loss, lossPct);
totalSent += c.SentCount;
totalRecv += c.ReceivedCount;
if (c.peer != null)
{
connected++;
}
}
Log.Information("────────────────────────────────────────────");
Log.Information(
"[TOTAL] Sent={Sent} Recv={Recv} Connected={Connected}/{Total}",
totalSent, totalRecv, connected, clients.Count);
Log.Information("────────────────────────────────────────────");
}
public void Stop()
{
foreach (DummyClients c in clients)
{
c.Stop();
}
Log.Information("[SERVICE] 모든 클라이언트 종료됨.");
}
}

View File

@@ -0,0 +1,170 @@
using System.Diagnostics;
using ClientTester.Packet;
using LiteNetLib;
using LiteNetLib.Utils;
using Serilog;
namespace ClientTester.DummyService;
public class DummyClients
{
private NetManager manager;
private EventBasedNetListener listener;
private NetDataWriter? writer;
public NetPeer? peer;
public long clientId; // 일단 이게 hashKey가 됨 => 0 ~ 1000번까지는 더미용응로 뺴둠
// info
private Vector3 position = new Vector3();
private int rotY = 0;
private float moveSpeed = 3.5f;
private float distance = 0.0f;
private float preTime = 0.0f;
// 이동 계산용
private readonly Stopwatch moveClock = Stopwatch.StartNew();
private float posX = 0f;
private float posZ = 0f;
private float dirX = 0f;
private float dirZ = 0f;
// 맵 경계
public MapBounds Map { get; set; } = new MapBounds(-50f, 50f, -50f, 50f);
// 통계
public int SentCount
{
set;
get;
}
public int ReceivedCount
{
set;
get;
}
public int RttCount
{
set;
get;
}
public DummyClients(long clientId, string ip, int port, string key)
{
this.clientId = clientId;
listener = new EventBasedNetListener();
manager = new NetManager(listener);
writer = new NetDataWriter();
listener.PeerConnectedEvent += netPeer =>
{
peer = netPeer;
Log.Information("[Client {ClientId:00}] 연결됨", this.clientId);
// clientID가 토큰의 hashKey라고 가정함
DummyAccTokenPacket recvTokenPacket = new DummyAccTokenPacket();
recvTokenPacket.Token = clientId;
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.DUMMY_ACC_TOKEN, recvTokenPacket);
writer.Put(data);
peer.Send(writer, DeliveryMethod.ReliableOrdered);
writer.Reset();
};
listener.NetworkReceiveEvent += (peer, reader, channel, deliveryMethod) =>
{
ReceivedCount++;
reader.Recycle();
};
listener.PeerDisconnectedEvent += (peer, info) =>
{
Log.Warning("[Client {ClientId:00}] 연결 끊김: {Reason}", this.clientId, info.Reason);
this.peer = null;
};
manager.Start();
manager.Connect(ip, port, key);
}
public void UpdateDummy()
{
// 델타 타임 계산 (초 단위)
float now = (float)moveClock.Elapsed.TotalSeconds;
float delta = preTime > 0f ? now - preTime : 0.1f;
preTime = now;
// 남은 거리가 없으면 새 방향·목표 거리 설정
if (distance <= 0f)
{
// 벽에 붙어있으면 반대 방향 강제, 아니면 ±30도 회전
int wallRotY = Map.GetRotYAwayFromWall(posX, posZ);
rotY = wallRotY >= 0
? (wallRotY + Random.Shared.Next(-30, 31) + 360) % 360
: (rotY + Random.Shared.Next(-30, 31) + 360) % 360;
float rad = rotY * MathF.PI / 180f;
dirX = MathF.Sin(rad);
dirZ = MathF.Cos(rad);
// 3초~12초에 도달할 수 있는 거리 = moveSpeed × 랜덤 초
float seconds = 3f + (float)Random.Shared.NextDouble() * 9f;
distance = moveSpeed * seconds;
}
// 이번 틱 이동량 (남은 거리 초과 방지)
float step = MathF.Min(moveSpeed * delta, distance);
float nextX = posX + dirX * step;
float nextZ = posZ + dirZ * step;
// 벽 충돌 시 clamp + 다음 틱에 방향 재설정
bool hitWall = Map.Clamp(ref nextX, ref nextZ);
posX = nextX;
posZ = nextZ;
distance = hitWall ? 0f : distance - step;
// 정수 Vector3 갱신
position.X = (int)MathF.Round(posX);
position.Z = (int)MathF.Round(posZ);
}
public void SendTransform()
{
if (peer == null || writer == null)
{
return;
}
UpdateDummy();
TransformPlayerPacket transformPlayerPacket = new TransformPlayerPacket
{
PlayerId = (int)clientId,
RotY = rotY,
Position = new Packet.Vector3
{
X = position.X,
Y = 0, // 높이는 버린다.
Z = position.Z
}
};
// Protobuf 직렬화 + 헤더 조립
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.TRANSFORM_PLAYER, transformPlayerPacket);
writer.Put(data);
// 이동은 손실 감수함
peer.Send(writer, DeliveryMethod.Unreliable);
SentCount++;
writer.Reset();
}
public void PollEvents()
{
manager.PollEvents();
}
public void Stop()
{
manager.Stop();
}
}

View File

@@ -0,0 +1,116 @@
namespace ClientTester.DummyService;
public class MapBounds
{
public float MinX
{
get;
set;
}
public float MaxX
{
get;
set;
}
public float MinZ
{
get;
set;
}
public float MaxZ
{
get;
set;
}
public MapBounds(float minX, float maxX, float minZ, float maxZ)
{
MinX = minX;
MaxX = maxX;
MinZ = minZ;
MaxZ = maxZ;
}
// 위치가 경계 안에 있는지 체크
public bool IsInside(float x, float z)
{
return x >= MinX && x <= MaxX && z >= MinZ && z <= MaxZ;
}
// 경계 초과 시 clamp, 벽에 부딪혔으면 true 반환
public bool Clamp(ref float x, ref float z)
{
bool hit = false;
if (x < MinX)
{
x = MinX;
hit = true;
}
else if (x > MaxX)
{
x = MaxX;
hit = true;
}
if (z < MinZ)
{
z = MinZ;
hit = true;
}
else if (z > MaxZ)
{
z = MaxZ;
hit = true;
}
return hit;
}
// 현재 위치 기준으로 벽 반대 방향 rotY 계산 (벽 없으면 -1)
public int GetRotYAwayFromWall(float x, float z, float margin = 0.5f)
{
bool atLeft = x <= MinX + margin;
bool atRight = x >= MaxX - margin;
bool atBottom = z <= MinZ + margin;
bool atTop = z >= MaxZ - margin;
if (!atLeft && !atRight && !atBottom && !atTop)
{
return -1; // 벽 근처 아님
}
// 벽 반대 방향 벡터 합산
float awayX = 0f, awayZ = 0f;
if (atLeft)
{
awayX += 1f;
}
if (atRight)
{
awayX -= 1f;
}
if (atBottom)
{
awayZ += 1f;
}
if (atTop)
{
awayZ -= 1f;
}
// 정규화
float len = MathF.Sqrt(awayX * awayX + awayZ * awayZ);
awayX /= len;
awayZ /= len;
// 방향 벡터 → rotY (degree)
return ((int)(MathF.Atan2(awayX, awayZ) * 180f / MathF.PI) + 360) % 360;
}
}

View File

@@ -3,9 +3,9 @@ using Serilog;
namespace ClientTester.EchoDummyService;
public class DummyClientService
public class EchoDummyClientService
{
private readonly List<DummyClients> clients;
private readonly List<EchoDummyClients> clients;
private readonly int sendInterval;
// 유닛 테스트용 (n패킷 시간체크)
@@ -24,10 +24,10 @@ public class DummyClientService
// 모든거 강종
public event Action? OnAllDisconnected;
public DummyClientService(int count, string ip, int port, string key, int sendIntervalMs = 1000)
public EchoDummyClientService(int count, string ip, int port, string key, int sendIntervalMs = 1000)
{
sendInterval = sendIntervalMs;
clients = Enumerable.Range(0, count).Select(i => new DummyClients(i, ip, port, key)).ToList();
clients = Enumerable.Range(0, count).Select(i => new EchoDummyClients(i, ip, port, key)).ToList();
Log.Information("[SERVICE] {Count}개 클라이언트 생성 → {Ip}:{Port}", count, ip, port);
}
@@ -36,7 +36,7 @@ public class DummyClientService
{
if (IsTest)
{
foreach (DummyClients c in clients)
foreach (EchoDummyClients c in clients)
{
c.TestCount = TestCount;
}
@@ -54,32 +54,18 @@ public class DummyClientService
{
while (!ct.IsCancellationRequested)
{
foreach (DummyClients c in clients)
foreach (EchoDummyClients c in clients)
{
c.PollEvents();
}
try
{
await Task.Delay(10, ct);
}
catch (OperationCanceledException)
{
break;
}
await Task.Delay(10);
}
}
private async Task SendLoopAsync(CancellationToken ct)
{
try
{
await Task.Delay(500, ct);
}
catch (OperationCanceledException)
{
return;
}
await Task.Delay(500);
int tick = 0;
@@ -88,7 +74,7 @@ public class DummyClientService
int sent = 0;
int total = clients.Count;
foreach (DummyClients client in clients)
foreach (EchoDummyClients client in clients)
{
client.SendPing();
if (client.peer != null)
@@ -111,14 +97,7 @@ public class DummyClientService
Log.Debug("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total);
tick++;
try
{
await Task.Delay(sendInterval, ct);
}
catch (OperationCanceledException)
{
break;
}
await Task.Delay(sendInterval);
}
}
@@ -132,7 +111,7 @@ public class DummyClientService
double totalAvgRtt = 0;
foreach (DummyClients c in clients)
foreach (EchoDummyClients c in clients)
{
NetStatistics? stats = c.peer?.Statistics;
long loss = stats?.PacketLoss ?? 0;
@@ -149,6 +128,7 @@ public class DummyClientService
totalAvgRtt += c.AvgRttMs;
rttClientCount++;
}
if (c.peer != null)
{
connected++;
@@ -166,7 +146,7 @@ public class DummyClientService
public void Stop()
{
foreach (DummyClients c in clients)
foreach (EchoDummyClients c in clients)
{
c.Stop();
}

View File

@@ -1,13 +1,15 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using ClientTester.Packet;
using LiteNetLib;
using LiteNetLib.Utils;
using ProtoBuf;
using Serilog;
namespace ClientTester.EchoDummyService;
public class DummyClients
public class EchoDummyClients
{
private NetManager manager;
private EventBasedNetListener listener;
@@ -18,7 +20,7 @@ public class DummyClients
// seq → 송신 타임스탬프 (Stopwatch tick)
private ConcurrentDictionary<int, long> pendingPings = new();
private int seqNumber;
private const int MaxPendingPings = 1000;
private const int MAX_PENDING_PINGS = 1000;
// 유닛 테스트용 (0 = 제한 없음)
public int TestCount
@@ -58,7 +60,7 @@ public class DummyClients
get;
}
public DummyClients(int clientId, string ip, int port, string key)
public EchoDummyClients(int clientId, string ip, int port, string key)
{
this.clientId = clientId;
listener = new EventBasedNetListener();
@@ -75,10 +77,14 @@ public class DummyClients
{
short code = reader.GetShort();
short bodyLength = reader.GetShort();
string? msg = reader.GetString();
byte[] payloadBytes = new byte[bodyLength];
reader.GetBytes(payloadBytes, bodyLength);
EchoPacket echoPacket = PacketSerializer.DeserializePayload<EchoPacket>(payloadBytes);
string msg = echoPacket.Str;
long sentTick;
if (msg != null && msg.StartsWith("Echo seq:") &&
if (msg.StartsWith("Echo seq:") &&
int.TryParse(msg.Substring("Echo seq:".Length), out int seq) &&
pendingPings.TryRemove(seq, out sentTick))
{
@@ -119,22 +125,24 @@ public class DummyClients
pendingPings[seq] = Stopwatch.GetTimestamp();
// 응답 없는 오래된 ping 정리 (패킷 유실 시 메모리 누수 방지)
if (pendingPings.Count > MaxPendingPings)
if (pendingPings.Count > MAX_PENDING_PINGS)
{
int cutoff = seq - MaxPendingPings;
int cutoff = seq - MAX_PENDING_PINGS;
foreach (int key in pendingPings.Keys)
{
if (key < cutoff)
{
pendingPings.TryRemove(key, out _);
}
}
}
PacketHeader packetHeader = new PacketHeader();
packetHeader.Code = 0;
packetHeader.BodyLength = $"Echo seq:{seq}".Length;
writer.Put((short)packetHeader.Code);
writer.Put((short)packetHeader.BodyLength);
writer.Put($"Echo seq:{seq}");
// string → raw bytes (길이 prefix 방지)
EchoPacket echoPacket = new EchoPacket();
echoPacket.Str = $"Echo seq:{seq}";
byte[] data = PacketSerializer.Serialize<EchoPacket>((ushort)PacketCode.ECHO, echoPacket);
writer.Put(data);
// 순서보장 안함 HOL Blocking 제거
peer.Send(writer, DeliveryMethod.ReliableUnordered);
SentCount++;

View File

@@ -0,0 +1,6 @@
namespace ClientTester.EchoDummyService;
public class Map
{
// TODO : 맵 정보 필요
}

View File

@@ -4,6 +4,22 @@ using ProtoBuf;
namespace ClientTester.Packet;
// ============================================================
// 에코용
// ============================================================
// ECHO
[ProtoContract]
public class EchoPacket
{
[ProtoMember(1)]
public string Str
{
get;
set;
}
}
// ============================================================
// 공통 타입
// ============================================================
@@ -100,31 +116,25 @@ public class PlayerInfo
}
}
[ProtoContract]
public class ItemInfo
{
[ProtoMember(1)]
public int ItemId
{
get;
set;
}
[ProtoMember(2)]
public int Count
{
get;
set;
}
}
// ============================================================
// 인증
// ============================================================
// RECV_TOKEN
// DUMMY_ACC_TOKEN
[ProtoContract]
public class RecvTokenPacket
public class DummyAccTokenPacket
{
[ProtoMember(1)]
public long Token
{
get;
set;
}
}
// ACC_TOKEN
[ProtoContract]
public class AccTokenPacket
{
[ProtoMember(1)]
public string Token
@@ -134,7 +144,7 @@ public class RecvTokenPacket
}
}
// LOAD_GAME
// LOAD_GAME 내 정보
[ProtoContract]
public class LoadGamePacket
{
@@ -151,27 +161,96 @@ public class LoadGamePacket
get;
set;
}
[ProtoMember(3)]
public int MaplId
{
get;
set;
}
}
// ============================================================
// 로비
// ============================================================
// INTO_LOBBY
[ProtoContract]
public class IntoLobbyPacket
public class ChannelInfo
{
[ProtoMember(1)]
public int ChannelId
{
get;
set;
}
[ProtoMember(2)]
public int ChannelUserConut
{
get;
set;
}
[ProtoMember(3)]
public int ChannelUserMax
{
get;
set;
}
}
[ProtoContract]
public class LoadChannelPacket
{
[ProtoMember(1)]
public List<ChannelInfo> Channels
{
get;
set;
} = new List<ChannelInfo>();
}
// INTO_CHANNEL 클라->서버: 입장할 채널 ID / 서버->클라: 채널 내 나 이외 플레이어 목록
[ProtoContract]
public class IntoChannelPacket
{
[ProtoMember(1)]
public int ChannelId
{
get;
set;
} // 클라->서버: 입장할 채널 ID
[ProtoMember(2)]
public List<PlayerInfo> Players
{
get;
set;
} = null!;
} = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록
}
// EXIT_LOBBY
// UPDATE_CHANNEL_USER 유저 접속/나감
[ProtoContract]
public class ExitLobbyPacket
public class UpdateChannelUserPacket
{
[ProtoMember(1)]
public PlayerInfo Players
{
get;
set;
}
[ProtoMember(2)]
public bool IsAdd
{
get;
set;
}
}
// EXIT_CHANNEL 나가는 유저
[ProtoContract]
public class ExitChannelPacket
{
[ProtoMember(1)]
public int PlayerId
@@ -181,174 +260,6 @@ public class ExitLobbyPacket
}
}
// ============================================================
// 인스턴스 던전
// ============================================================
public enum BossState
{
START,
END,
PHASE_CHANGE
}
public enum BossResult
{
SUCCESS,
FAIL
}
// INTO_INSTANCE
[ProtoContract]
public class IntoInstancePacket
{
[ProtoMember(1)]
public int InstanceId
{
get;
set;
}
[ProtoMember(2)]
public int BossId
{
get;
set;
}
[ProtoMember(3)]
public List<int> PlayerIds
{
get;
set;
}
}
// UPDATE_BOSS
[ProtoContract]
public class UpdateBossPacket
{
[ProtoMember(1)]
public BossState State
{
get;
set;
}
[ProtoMember(2)]
public int Phase
{
get;
set;
}
[ProtoMember(3)]
public BossResult Result
{
get;
set;
} // END일 때만 유효
}
// REWARD_INSTANCE
[ProtoContract]
public class RewardInstancePacket
{
[ProtoMember(1)]
public int Exp
{
get;
set;
}
[ProtoMember(2)]
public List<ItemInfo> Items
{
get;
set;
}
}
// EXIT_INSTANCE
[ProtoContract]
public class ExitInstancePacket
{
[ProtoMember(1)]
public int PlayerId
{
get;
set;
}
}
// ============================================================
// 파티
// ============================================================
public enum PartyUpdateType
{
CREATE,
DELETE
}
public enum UserPartyUpdateType
{
JOIN,
LEAVE
}
// UPDATE_PARTY
[ProtoContract]
public class UpdatePartyPacket
{
[ProtoMember(1)]
public int PartyId
{
get;
set;
}
[ProtoMember(2)]
public PartyUpdateType Type
{
get;
set;
}
[ProtoMember(3)]
public int LeaderId
{
get;
set;
}
}
// UPDATE_USER_PARTY
[ProtoContract]
public class UpdateUserPartyPacket
{
[ProtoMember(1)]
public int PartyId
{
get;
set;
}
[ProtoMember(2)]
public int PlayerId
{
get;
set;
}
[ProtoMember(3)]
public UserPartyUpdateType Type
{
get;
set;
}
}
// ============================================================
// 플레이어
// ============================================================
@@ -604,3 +515,71 @@ public class DamagePacket
set;
}
}
// ============================================================
// 파티
// ============================================================
public enum PartyUpdateType
{
CREATE,
DELETE
}
public enum UserPartyUpdateType
{
JOIN,
LEAVE
}
// UPDATE_PARTY
[ProtoContract]
public class UpdatePartyPacket
{
[ProtoMember(1)]
public int PartyId
{
get;
set;
}
[ProtoMember(2)]
public PartyUpdateType Type
{
get;
set;
}
[ProtoMember(3)]
public int LeaderId
{
get;
set;
}
}
// UPDATE_USER_PARTY
[ProtoContract]
public class UpdateUserPartyPacket
{
[ProtoMember(1)]
public int PartyId
{
get;
set;
}
[ProtoMember(2)]
public int PlayerId
{
get;
set;
}
[ProtoMember(3)]
public UserPartyUpdateType Type
{
get;
set;
}
}

View File

@@ -1,61 +1,62 @@
namespace ClientTester.Packet;
public enum PacketCode : short
public enum PacketCode : ushort
{
NONE,
// ECHO
ECHO = 1000,
// DUMMY 클라는 이걸로 jwt토큰 안받음
DUMMY_ACC_TOKEN = 1001,
// 초기 클라이언트 시작시 jwt토큰 받아옴
RECV_TOKEN,
// jwt토큰 검증후 게임에 들어갈지 말지 (내 데이터도 전송)
ACC_TOKEN = 1,
// 내 정보 로드 (서버 -> 클라)
LOAD_GAME,
// 마을(로비)진입시 모든 데이터 로드
INTO_LOBBY,
// 모든 채널 로드 - jwt토큰 검증후 게임에 들어갈지 말지 (내 데이터도 전송)
// (서버 -> 클라)
LOAD_CHANNEL,
// 로비 나가기
EXIT_LOBBY,
// 나 채널 접속 (클라 -> 서버)
INTO_CHANNEL,
// 인스턴스 던전 입장
INTO_INSTANCE,
// 새로운 유저 채널 접속 (서버 -> 클라) / 유저 채널 나감 (서버 -> 클라)
UPDATE_CHANNEL_USER,
// 결과 보상
REWARD_INSTANCE,
// 채널 나가기 (클라 -> 서버)
EXIT_CHANNEL,
// 보스전 (시작, 종료)
UPDATE_BOSS,
// 플레이어 위치, 방향 (서버 -> 클라 \ 클라 -> 서버)
TRANSFORM_PLAYER,
// 인스턴스 던전 퇴장
EXIT_INSTANCE,
// 플레이어 행동 업데이트 (서버 -> 클라 \ 클라 -> 서버)
ACTION_PLAYER,
// 플레이어 스테이트 업데이트 (서버 -> 클라 \ 클라 -> 서버)
STATE_PLAYER,
// NPC 위치, 방향 (서버 -> 클라)
TRANSFORM_NPC,
// NPC 행동 업데이트 (서버 -> 클라)
ACTION_NPC,
// NPC 스테이트 업데이트 (서버 -> 클라)
STATE_NPC,
// 데미지 UI 전달 (서버 -> 클라)
DAMAGE,
// 파티 (생성, 삭제)
UPDATE_PARTY,
// 파티 유저 업데이트(추가 삭제)
UPDATE_USER_PARTY,
// 플레이어 위치, 방향
TRANSFORM_PLAYER,
// 플레이어 행동 업데이트
ACTION_PLAYER,
// 플레이어 스테이트 업데이트
STATE_PLAYER,
// NPC 위치, 방향
TRANSFORM_NPC,
// NPC 행동 업데이트
ACTION_NPC,
// NPC 스테이트 업데이트
STATE_NPC,
// 데미지 UI 전달
DAMAGE
UPDATE_USER_PARTY
}
public class PacketHeader
{
public PacketCode Code;
public int BodyLength;
public ushort BodyLength;
}

View File

@@ -11,15 +11,18 @@ namespace ClientTester.Packet
public static byte[] Serialize<T>(ushort type, T packet)
{
using MemoryStream payloadMs = new MemoryStream();
Serializer.Serialize(payloadMs, packet);
Serializer.Serialize<T>(payloadMs, packet);
byte[] payload = payloadMs.ToArray();
ushort size = (ushort)payload.Length;
byte[] result = new byte[4 + payload.Length];
// 2바이트 패킷 타입 헤더
result[0] = (byte)(type & 0xFF);
result[1] = (byte)(type >> 8);
// 2바이트 패킷 길이 헤더
result[2] = (byte)(size & 0xFF);
result[3] = (byte)(size >> 8);
// protobuf 페이로드
Buffer.BlockCopy(payload, 0, result, 4, payload.Length);
return result;
}
@@ -36,10 +39,12 @@ namespace ClientTester.Packet
ushort type = (ushort)(data[0] | (data[1] << 8));
ushort size = (ushort)(data[2] | (data[3] << 8));
// 헤더에 명시된 size와 실제 데이터 길이 검증
int actualPayloadLen = data.Length - 4;
if (size > actualPayloadLen)
{
Log.Warning("[PacketSerializer] 페이로드 크기 불일치 HeaderSize={Size} ActualSize={Actual}", size, actualPayloadLen);
Log.Warning("[PacketSerializer] 페이로드 크기 불일치 HeaderSize={Size} ActualSize={Actual}", size,
actualPayloadLen);
return (0, 0, null)!;
}

View File

@@ -1,25 +1,18 @@
using ClientTester.DummyService;
using ClientTester.EchoDummyService;
using Serilog;
class EcoClientTester
{
public static readonly string SERVER_IP = "tolelom.xyz";
public static readonly string SERVER_IP = "localhost";
public static readonly int SERVER_PORT = 9500;
public static readonly string CONNECTION_KEY = "test";
public static readonly int CLIENT_COUNT = 100;
public static readonly int CLIENT_COUNT = 10;
private static async Task Main(string[] args)
private async Task StartEchoDummyTest()
{
try
{
// .MinimumLevel.Warning() // Warning 이상만 출력 배포시
string timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File($"logs/log_{timestamp}.txt")
.CreateLogger();
CancellationTokenSource cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
@@ -28,7 +21,8 @@ class EcoClientTester
cts.Cancel();
};
DummyClientService service = new DummyClientService(CLIENT_COUNT, SERVER_IP, SERVER_PORT, CONNECTION_KEY, 100);
EchoDummyClientService service =
new EchoDummyClientService(CLIENT_COUNT, SERVER_IP, SERVER_PORT, CONNECTION_KEY, 100);
service.OnAllDisconnected += () =>
{
Log.Warning("[SHUTDOWN] 종료 이벤트 발생, 종료 중...");
@@ -44,4 +38,79 @@ class EcoClientTester
await Log.CloseAndFlushAsync();
}
catch (Exception e)
{
Log.Error($"[SHUTDOWN] 예외 발생 : {e}");
}
}
private async Task StartDummyTest()
{
try
{
CancellationTokenSource cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
Log.Warning("[SHUTDOWN] Ctrl+C 감지, 종료 중...");
cts.Cancel();
};
DummyClientService service =
new DummyClientService(CLIENT_COUNT, SERVER_IP, SERVER_PORT, CONNECTION_KEY, 100);
service.OnAllDisconnected += () =>
{
Log.Warning("[SHUTDOWN] 종료 이벤트 발생, 종료 중...");
cts.Cancel();
};
await service.RunAsync(cts.Token);
service.PrintStats();
service.Stop();
await Log.CloseAndFlushAsync();
}
catch (Exception e)
{
Log.Error($"[SHUTDOWN] 예외 발생 : {e}");
}
}
private static async Task Main(string[] args)
{
// .MinimumLevel.Warning() // Warning 이상만 출력 배포시
string timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File($"logs2/log_{timestamp}.txt")
.CreateLogger();
Log.Information("========== 더미 클라 테스터 ==========");
Log.Information("1. 에코 서버");
Log.Information("2. 더미 클라(이동만)");
Log.Information("====================================");
Log.Information("1 / 2 : ");
string? input = Console.ReadLine();
if (!int.TryParse(input, out int choice) || (choice != 1 && choice != 2))
{
Log.Warning("1 또는 2만 입력하세요.");
return;
}
EcoClientTester tester = new EcoClientTester();
if (choice == 1)
{
// 에코 서버 실행
await tester.StartEchoDummyTest();
}
else if (choice == 2)
{
// 더미 클라 실행
await tester.StartDummyTest();
}
}
}

View File

@@ -0,0 +1,8 @@
namespace ClientTester;
public class Vector3
{
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
}

View File

@@ -0,0 +1,65 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using MMOserver.Utils;
using Serilog;
namespace MMOserver.Api;
public class RestApi : Singleton<RestApi>
{
private const string VERIFY_URL = "https://a301.api.tolelom.xyz/api/auth/verify";
private readonly HttpClient httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
private const int MAX_RETRY = 3;
private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(1);
// 토큰 검증 - 성공 시 username 반환
// 401 → 재시도 없이 즉시 null 반환 (토큰 자체가 무효)
// 타임아웃/네트워크 오류 → 최대 MAX_RETRY회 재시도 후 null 반환
public async Task<string?> VerifyTokenAsync(string token)
{
for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
{
try
{
HttpResponseMessage response = await httpClient.PostAsJsonAsync(VERIFY_URL, new { token });
// 401: 토큰 자체가 무효 → 재시도해도 같은 결과, 즉시 반환
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Log.Warning("[RestApi] 토큰 인증 실패 (401)");
return null;
}
response.EnsureSuccessStatusCode();
AuthVerifyResponse? result = await response.Content.ReadFromJsonAsync<AuthVerifyResponse>();
return result?.Username;
}
catch (Exception ex) when (attempt < MAX_RETRY)
{
// 일시적 장애 (타임아웃, 네트워크 오류 등) → 재시도
Log.Warning("[RestApi] 통신 실패 (시도 {Attempt}/{Max}): {Message}", attempt, MAX_RETRY, ex.Message);
await Task.Delay(RETRY_DELAY);
}
catch (Exception ex)
{
// 마지막 시도까지 실패
Log.Error("[RestApi] 최종 통신 실패 ({Max}회 시도): {Message}", MAX_RETRY, ex.Message);
}
}
return null;
}
private sealed class AuthVerifyResponse
{
[JsonPropertyName("username")]
public string? Username
{
get;
set;
}
}
}

View File

@@ -21,7 +21,7 @@ public class ChannelManager
public void Initializer(int channelSize = 1)
{
for (int i = 0; i < channelSize; i++)
for (int i = 0; i <= channelSize; i++)
{
channels.Add(new Channel(i));
}
@@ -40,7 +40,7 @@ public class ChannelManager
public void AddUser(int channelId, long userId, Player player)
{
// 유저 추가
connectUsers[userId] = channelId;
connectUsers.Add(userId, channelId);
// 채널에 유저 추가
channels[channelId].AddUser(userId, player);
}

View File

@@ -1,6 +1,9 @@
using LiteNetLib;
using LiteNetLib.Utils;
using MMOserver.Api;
using MMOserver.Game.Channel;
using MMOserver.Packet;
using MMOserver.Utils;
using ProtoBuf;
using Serilog;
using ServerLib.Packet;
@@ -24,6 +27,103 @@ public class GameServer : ServerBase
};
}
protected override void HandleEcho(NetPeer peer, byte[] payload)
{
if (payload.Length < 4)
{
Log.Warning("[Server] Echo 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
return;
}
// 세션에 넣지는 않는다.
NetDataReader reader = new NetDataReader(payload);
short code = reader.GetShort();
short bodyLength = reader.GetShort();
EchoPacket echoPacket = Serializer.Deserialize<EchoPacket>(payload.AsMemory(4));
Log.Debug("[Echo] : addr={Addr}, str={Str}", peer.Address, echoPacket.Str);
// Echo메시지는 순서보장 안함 HOL Blocking 제거
SendTo(peer, payload, DeliveryMethod.ReliableUnordered);
}
protected override void HandleAuthDummy(NetPeer peer, byte[] payload)
{
DummyAccTokenPacket accTokenPacket = Serializer.Deserialize<DummyAccTokenPacket>(new ReadOnlyMemory<byte>(payload));
long hashKey = accTokenPacket.Token;
if (sessions.TryGetValue(hashKey, out NetPeer? existing))
{
// WiFi → LTE 전환 등 재연결: 이전 피어 교체
existing.Tag = null;
sessions.Remove(hashKey);
Log.Information("[Server] 재연결 HashKey={Key} Old={Old} New={New}", hashKey, existing.Id, peer.Id);
existing.Disconnect();
}
peer.Tag = new Session(hashKey, peer);
sessions[hashKey] = peer;
pendingPeers.Remove(peer.Id);
if (hashKey <= 1000)
{
// 더미 클라다.
ChannelManager cm = ChannelManager.Instance;
cm.AddUser(1, hashKey, new Player());
}
else
{
Log.Error("[Server] Dummy 클라이언트가 아닙니다. 연결을 종료합니다. HashKey={Key} PeerId={Id}", hashKey, peer.Id);
peer.Disconnect();
return;
}
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
OnSessionConnected(peer, hashKey);
}
protected override async void HandleAuth(NetPeer peer, byte[] payload)
{
AccTokenPacket accTokenPacket = Serializer.Deserialize<AccTokenPacket>(new ReadOnlyMemory<byte>(payload));
string token = accTokenPacket.Token;
tokenHash.TryGetValue(token, out long hashKey);
if (hashKey <= 1000)
{
hashKey = UuidGeneratorManager.Instance.Create();
}
if (sessions.TryGetValue(hashKey, out NetPeer? existing))
{
// WiFi → LTE 전환 등 재연결: 이전 피어 교체 (토큰 재검증 불필요)
existing.Tag = null;
sessions.Remove(hashKey);
Log.Information("[Server] 재연결 HashKey={Key} Old={Old} New={New}", hashKey, existing.Id, peer.Id);
existing.Disconnect();
}
else
{
// 신규 연결: 웹서버에 JWT 검증 요청
string? username = await RestApi.Instance.VerifyTokenAsync(token);
if (username == null)
{
Log.Warning("[Server] 토큰 검증 실패 - 연결 거부 PeerId={Id}", peer.Id);
UuidGeneratorManager.Instance.Release(hashKey);
peer.Disconnect();
return;
}
Log.Information("[Server] 토큰 검증 성공 Username={Username} PeerId={Id}", username, peer.Id);
}
peer.Tag = new Session(hashKey, peer);
((Session)peer.Tag).Token = token;
sessions[hashKey] = peer;
tokenHash[token] = hashKey;
pendingPeers.Remove(peer.Id);
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
OnSessionConnected(peer, hashKey);
}
protected override void OnSessionConnected(NetPeer peer, long hashKey)
{
Log.Information("[GameServer] 세션 연결 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
@@ -51,6 +151,7 @@ public class GameServer : ServerBase
{
Log.Information("[GameServer] 세션 해제 HashKey={Key} Reason={Reason}", hashKey, info.Reason);
}
UuidGeneratorManager.Instance.Release(hashKey);
}
protected override void HandlePacket(NetPeer peer, long hashKey, ushort type, byte[] payload)

View File

@@ -4,6 +4,22 @@ using ProtoBuf;
namespace MMOserver.Packet;
// ============================================================
// 에코용
// ============================================================
// ECHO
[ProtoContract]
public class EchoPacket
{
[ProtoMember(1)]
public string Str
{
get;
set;
}
}
// ============================================================
// 공통 타입
// ============================================================
@@ -104,9 +120,21 @@ public class PlayerInfo
// 인증
// ============================================================
// RECV_TOKEN
// DUMMY_ACC_TOKEN
[ProtoContract]
public class RecvTokenPacket
public class DummyAccTokenPacket
{
[ProtoMember(1)]
public long Token
{
get;
set;
}
}
// ACC_TOKEN
[ProtoContract]
public class AccTokenPacket
{
[ProtoMember(1)]
public string Token

View File

@@ -2,8 +2,14 @@ namespace MMOserver.Packet;
public enum PacketCode : ushort
{
// ECHO
ECHO = 1000,
// DUMMY 클라는 이걸로 jwt토큰 안받음
DUMMY_ACC_TOKEN = 1001,
// 초기 클라이언트 시작시 jwt토큰 받아옴
RECV_TOKEN,
ACC_TOKEN = 1,
// 내 정보 로드 (서버 -> 클라)
LOAD_GAME,

View File

@@ -0,0 +1,12 @@
namespace MMOserver.Utils;
public abstract class Singleton<T> where T : Singleton<T>, new()
{
private static readonly Lazy<T> instance = new Lazy<T>(static () => new T(), LazyThreadSafetyMode.ExecutionAndPublication);
public static T Instance => instance.Value;
protected Singleton()
{
}
}

View File

@@ -0,0 +1,35 @@
namespace MMOserver.Utils;
public class UuidGeneratorManager : Singleton<UuidGeneratorManager>
{
// 0 ~ 1000 은 더미 클라이언트 예약 범위
private const long DUMMY_RANGE_MAX = 1000;
private readonly object idLock = new();
private readonly HashSet<long> usedIds = new();
// 고유 랜덤 long ID 발급 (1001번 이상, 충돌 시 재생성)
public long Create()
{
lock (idLock)
{
long id;
do
{
id = Random.Shared.NextInt64(DUMMY_RANGE_MAX + 1, long.MaxValue);
} while (usedIds.Contains(id));
usedIds.Add(id);
return id;
}
}
// 로그아웃 / 세션 만료 시 ID 반납
public bool Release(long id)
{
lock (idLock)
{
return usedIds.Remove(id);
}
}
}

View File

@@ -43,7 +43,7 @@ namespace ServerLib.Packet
// 헤더에 명시된 size와 실제 데이터 길이 검증
int actualPayloadLen = data.Length - 4;
if (size > actualPayloadLen)
if (size != actualPayloadLen)
{
Log.Warning("[PacketSerializer] 페이로드 크기 불일치 HeaderSize={Size} ActualSize={Actual}", size, actualPayloadLen);
return (0, 0, null)!;

View File

@@ -6,6 +6,7 @@ namespace ServerLib.Packet;
/// </summary>
public enum PacketType : ushort
{
Auth = 1, // 클라 → 서버: 최초 인증 (HashKey 전달)
ACC_TOKEN = 1, // 클라 → 서버: 최초 인증 (HashKey 전달)
DUMMY_ACC_TOKEN = 1001,
// 1000번 이상은 게임 패킷으로 예약
}

View File

@@ -30,12 +30,15 @@ public abstract class ServerBase : INetEventListener
protected NetManager netManager = null!;
// 인증 전 대기 피어 (peer.Id → NetPeer)
private readonly Dictionary<int, NetPeer> pendingPeers = new();
protected readonly Dictionary<int, NetPeer> pendingPeers = new();
// 인증된 세션 (hashKey → NetPeer) 재연결 조회용
// peer → hashKey 역방향은 peer.Tag as Session 으로 대체
protected readonly Dictionary<long, NetPeer> sessions = new();
// Token / HashKey 관리
protected readonly Dictionary<string, long> tokenHash = new();
// 재사용 NetDataWriter (단일 스레드 폴링이므로 안전)
private readonly NetDataWriter cachedWriter = new();
@@ -123,6 +126,12 @@ public abstract class ServerBase : INetEventListener
// (재연결로 이미 교체된 경우엔 건드리지 않음)
if (sessions.TryGetValue(session.HashKey, out NetPeer? current) && current.Id == peer.Id)
{
// 더미 클라 아니면 token관리
if (!string.IsNullOrEmpty(session.Token))
{
tokenHash.Remove(session.Token);
}
sessions.Remove(session.HashKey);
Log.Information("[Server] 세션 해제 HashKey={Key} Reason={Reason}", session.HashKey, disconnectInfo.Reason);
OnSessionDisconnected(peer, session.HashKey, disconnectInfo);
@@ -149,18 +158,23 @@ public abstract class ServerBase : INetEventListener
}
// 0이라면 에코 서버 테스트용 따로 처리
if (type == 0)
if (type == 1000)
{
HandleEcho(peer, data);
return;
}
// Auth 패킷은 베이스에서 처리 (raw 8-byte long, protobuf 불필요)
if (type == (ushort)PacketType.Auth)
if (type == (ushort)PacketType.ACC_TOKEN)
{
HandleAuth(peer, payload);
return;
}
else if (type == (ushort)PacketType.DUMMY_ACC_TOKEN)
{
HandleAuthDummy(peer, payload);
return;
}
// 인증된 피어인지 확인
if (peer.Tag is not Session session)
@@ -202,52 +216,15 @@ public abstract class ServerBase : INetEventListener
// Echo 서버 테스트
private void HandleEcho(NetPeer peer, byte[] payload)
{
if (payload.Length < 4)
{
Log.Warning("[Server] Echo 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
return;
}
protected abstract void HandleEcho(NetPeer peer, byte[] payload);
// 세션에 넣지는 않는다.
NetDataReader reader = new NetDataReader(payload);
short code = reader.GetShort();
short bodyLength = reader.GetShort();
Log.Debug("[Echo] : addr={Addr}, str={Str}", peer.Address, reader.GetString());
// Echo메시지는 순서보장 안함 HOL Blocking 제거
SendTo(peer, payload, DeliveryMethod.ReliableUnordered);
}
// ─── Auth 처리 (더미) ────────────────────────────────────────────────
// ─── Auth 처리 (내부) ────────────────────────────────────────────────
protected abstract void HandleAuthDummy(NetPeer peer, byte[] payload);
private void HandleAuth(NetPeer peer, byte[] payload)
{
if (payload.Length < sizeof(long))
{
Log.Warning("[Server] Auth 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
peer.Disconnect();
return;
}
// ─── Auth 처리 ────────────────────────────────────────────────
long hashKey = BitConverter.ToInt64(payload, 0);
if (sessions.TryGetValue(hashKey, out NetPeer? existing))
{
// WiFi → LTE 전환 등 재연결: 이전 피어 교체
existing.Tag = null;
sessions.Remove(hashKey);
Log.Information("[Server] 재연결 HashKey={Key} Old={Old} New={New}", hashKey, existing.Id, peer.Id);
existing.Disconnect();
}
peer.Tag = new Session(hashKey, peer);
sessions[hashKey] = peer;
pendingPeers.Remove(peer.Id);
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
OnSessionConnected(peer, hashKey);
}
protected abstract void HandleAuth(NetPeer peer, byte[] payload);
// ─── 전송 헬퍼 ───────────────────────────────────────────────────────

View File

@@ -4,12 +4,28 @@ namespace ServerLib.Service;
public class Session
{
public long HashKey { get; init; }
public NetPeer Peer { get; set; }
public string? Token
{
get;
set;
}
public long HashKey
{
get;
init;
}
public NetPeer Peer
{
get;
set;
}
public Session(long hashKey, NetPeer peer)
{
HashKey = hashKey;
Peer = peer;
Token = null;
}
}