16 Commits

Author SHA1 Message Date
qornwh1
8f49d3a5b4 fix : 포매팅, dead 코드 제거, 패킷 1번 수정 2026-03-04 10:50:42 +09:00
qornwh1
4ef58c2fad feat : 이동 패킷 전달 2026-03-04 10:02:48 +09:00
qornwh1
d16e4a05e5 fix : await 버그 픽스 2026-03-04 09:11:04 +09:00
qornwh1
9930348d5e feat : 더미 플레이어 구현 / 더미클라 서비스 에코용, 더미 플레이어용 분기 2026-03-04 08:55:27 +09:00
qornwh1
d2ba2ccb48 fix : 포매팅 2026-03-03 17:47:32 +09:00
qornwh1
27f3832894 fix : 수정후 리드미 정리 2026-03-03 17:43:32 +09:00
qornwh1
f75d71c1ee feat : 채널 매니저(각 채널, 유저 관리) 구현 / 유저 정보 구현 / 패킷 이동 채널 접속 구현 2026-03-03 17:43:07 +09:00
qornwh1
a9e1d2acaf feat : 파일 네이밍 변경, 변수 라인 변경 2026-03-03 15:08:13 +09:00
qornwh1
e3f365877b Merge branch 'fix_by_claude' of https://git.tolelom.xyz/A301/a301_mmo_game_server 2026-03-03 15:01:53 +09:00
qornwh1
01d107def3 feat : 패킷 전송완료 개수 시간 체크 기능 추가 2026-03-03 09:07:18 +09:00
6f164b6cdb docs : 수용 인원 추정 및 하드웨어/네트워크 요구사항 추가
- 현재 및 개선 단계별 CCU 추정 (현재 30~50명 → Phase 전체 적용 시 5,000명)
- M4 Mac Mini 기준 하드웨어 적합성 분석
- CCU별 네트워크 대역폭 계산 (AOI 적용 후 기준)
- 환경별 (가정용/IDC/클라우드) 현실적 CCU 결론

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 01:22:44 +09:00
f3eaeac37b docs : MMORPG 아키텍처 적합성 분석 보고서 추가
현재 서버 구조의 MMORPG 적합성 평가 (2.1/10)
게임 루프, AOI, 존 관리, 엔티티 시스템 등 미구현 영역 분석
Phase 1~5 전환 로드맵 포함

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 01:16:06 +09:00
cf2be6b125 fix : 코드 분석 후 버그 및 결함 16건 수정
- ARepository 전체 메서드 IDbConnection using 추가 (커넥션 풀 누수)
- GameServer NotImplementedException → 로그 출력으로 변경
- ServerBase Auth/Echo payload 길이 검증 주석 해제
- PacketSerializer MemoryStream using 추가 (양쪽 솔루션)
- PacketSerializer size 파라미터 제거, 자동 계산 + size 검증 구현
- ServerBase NetDataWriter cachedWriter 재사용 (GC 압력 감소)
- ServerBase isListening volatile 추가
- ServerBase Deserialize 실패 시 null payload 체크
- ServerBase Serilog 구조적 로깅 템플릿 구문 수정
- TestHandler 전체 메서드 try-catch 추가
- TestRepository IDbConnectionFactory 인터페이스로 변경
- DummyClients BodyLength 계산 불일치 수정
- DummyClients pendingPings 메모리 누수 방지
- EchoClientTester async void 이벤트 → 동기 Cancel()로 변경
- ANALYSIS.md 코드 분석 및 문제점 보고서 추가

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 01:09:27 +09:00
qornwh1
d73487df5b fix : 로그레벨 변경 2026-03-02 17:47:27 +09:00
qornwh1
66d18cd0ac feat : 나중 구조적 통합을 위해 main쪽 비동기 로직으로 변경 2026-03-02 17:47:03 +09:00
qornwh1
961973ff8b fix : writer 전역으로 변경, pendingPings 락 프리 Cuncurrent로 변경 2026-03-02 17:17:17 +09:00
25 changed files with 1618 additions and 613 deletions

View File

@@ -1,7 +1,7 @@
using LiteNetLib;
using Serilog;
namespace ClientTester.EchoDummyService;
namespace ClientTester.DummyService;
public class DummyClientService
{
@@ -14,17 +14,14 @@ public class DummyClientService
public DummyClientService(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(1, count + 1).Select(i => new DummyClients(i, ip, port, key)).ToList();
Log.Information("[SERVICE] {Count}개 클라이언트 생성 → {Ip}:{Port}", count, ip, port);
}
public async Task RunAsync(CancellationToken ct)
{
await Task.WhenAll(
PollLoopAsync(ct),
SendLoopAsync(ct)
);
await Task.WhenAll(PollLoopAsync(ct), SendLoopAsync(ct));
}
private async Task PollLoopAsync(CancellationToken ct)
@@ -38,7 +35,7 @@ public class DummyClientService
try
{
await Task.Delay(15, ct);
await Task.Delay(10, ct);
}
catch (OperationCanceledException)
{
@@ -67,7 +64,7 @@ public class DummyClientService
foreach (DummyClients client in clients)
{
client.SendPing();
client.SendTransform();
if (client.peer != null)
{
sent++;
@@ -85,7 +82,7 @@ public class DummyClientService
break;
}
Log.Information("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total);
Log.Debug("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total);
tick++;
try
@@ -106,8 +103,6 @@ public class DummyClientService
Log.Information("───────────── Performance Report ─────────────");
double totalAvgRtt = 0;
foreach (DummyClients c in clients)
{
NetStatistics? stats = c.peer?.Statistics;
@@ -115,24 +110,22 @@ public class DummyClientService
float lossPct = stats?.PacketLossPercent ?? 0f;
Log.Information(
"[Client {ClientId:00}] Sent={Sent} Recv={Recv} | Loss={Loss}({LossPct:F1}%) AvgRTT={AvgRtt:F3}ms LastRTT={LastRtt:F3}ms",
c.clientId, c.SentCount, c.ReceivedCount, loss, lossPct, c.AvgRttMs, c.LastRttMs);
"[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;
totalAvgRtt += c.AvgRttMs;
if (c.peer != null)
{
connected++;
}
}
double avgRtt = connected > 0 ? totalAvgRtt / connected : 0;
Log.Information("────────────────────────────────────────────");
Log.Information(
"[TOTAL] Sent={Sent} Recv={Recv} Connected={Connected}/{Total} AvgRTT={AvgRtt:F3}ms",
totalSent, totalRecv, connected, clients.Count, avgRtt);
"[TOTAL] Sent={Sent} Recv={Recv} Connected={Connected}/{Total}",
totalSent, totalRecv, connected, clients.Count);
Log.Information("────────────────────────────────────────────");
}

View File

@@ -0,0 +1,167 @@
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 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라고 가정함
AccTokenPacket recvTokenPacket = new AccTokenPacket();
recvTokenPacket.Token = clientId;
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.ACC_TOKEN, recvTokenPacket);
writer.Put(data);
peer.Send(writer, DeliveryMethod.ReliableOrdered);
writer.Reset();
};
listener.NetworkReceiveEvent += (peer, reader, channel, deliveryMethod) =>
{
short code = reader.GetShort();
short bodyLength = reader.GetShort();
string? msg = reader.GetString();
if (msg != null)
{
RttCount++;
}
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~+30도 범위로 회전
rotY = (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);
posX += dirX * step;
posZ += dirZ * step;
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,177 @@
using LiteNetLib;
using Serilog;
namespace ClientTester.EchoDummyService;
public class EchoDummyClientService
{
private readonly List<EchoDummyClients> clients;
private readonly int sendInterval;
// 유닛 테스트용 (n패킷 시간체크)
public bool IsTest
{
get;
set;
} = false;
public int TestCount
{
get;
set;
} = 100000;
// 모든거 강종
public event Action? OnAllDisconnected;
public EchoDummyClientService(int count, string ip, int port, string key, int sendIntervalMs = 1000)
{
sendInterval = sendIntervalMs;
clients = Enumerable.Range(0, count).Select(i => new EchoDummyClients(i, ip, port, key)).ToList();
Log.Information("[SERVICE] {Count}개 클라이언트 생성 → {Ip}:{Port}", count, ip, port);
}
public async Task RunAsync(CancellationToken ct)
{
if (IsTest)
{
foreach (EchoDummyClients c in clients)
{
c.TestCount = TestCount;
}
Log.Information("[TEST] 유닛 테스트 모드: 클라이언트당 {Count}개 수신 시 자동 종료", TestCount);
}
await Task.WhenAll(
PollLoopAsync(ct),
SendLoopAsync(ct)
);
}
private async Task PollLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
foreach (EchoDummyClients c in clients)
{
c.PollEvents();
}
try
{
await Task.Delay(10, ct);
}
catch (OperationCanceledException)
{
break;
}
}
}
private async Task SendLoopAsync(CancellationToken ct)
{
try
{
await Task.Delay(500, ct);
}
catch (OperationCanceledException)
{
return;
}
int tick = 0;
while (!ct.IsCancellationRequested)
{
int sent = 0;
int total = clients.Count;
foreach (EchoDummyClients client in clients)
{
client.SendPing();
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++;
try
{
await Task.Delay(sendInterval, ct);
}
catch (OperationCanceledException)
{
break;
}
}
}
public void PrintStats()
{
int totalSent = 0, totalRecv = 0;
int connected = 0;
int rttClientCount = 0;
Log.Information("───────────── Performance Report ─────────────");
double totalAvgRtt = 0;
foreach (EchoDummyClients 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}%) AvgRTT={AvgRtt:F3}ms LastRTT={LastRtt:F3}ms",
c.clientId, c.SentCount, c.ReceivedCount, loss, lossPct, c.AvgRttMs, c.LastRttMs);
totalSent += c.SentCount;
totalRecv += c.ReceivedCount;
if (c.RttCount > 0)
{
totalAvgRtt += c.AvgRttMs;
rttClientCount++;
}
if (c.peer != null)
{
connected++;
}
}
double avgRtt = rttClientCount > 0 ? totalAvgRtt / rttClientCount : 0;
Log.Information("────────────────────────────────────────────");
Log.Information(
"[TOTAL] Sent={Sent} Recv={Recv} Connected={Connected}/{Total} AvgRTT={AvgRtt:F3}ms",
totalSent, totalRecv, connected, clients.Count, avgRtt);
Log.Information("────────────────────────────────────────────");
}
public void Stop()
{
foreach (EchoDummyClients c in clients)
{
c.Stop();
}
Log.Information("[SERVICE] 모든 클라이언트 종료됨.");
}
}

View File

@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using ClientTester.Packet;
using LiteNetLib;
@@ -6,16 +7,25 @@ using Serilog;
namespace ClientTester.EchoDummyService;
public class DummyClients
public class EchoDummyClients
{
public NetManager manager;
public EventBasedNetListener listener;
private NetManager manager;
private EventBasedNetListener listener;
private NetDataWriter? writer;
public NetPeer? peer;
public int clientId;
// seq → 송신 타임스탬프 (Stopwatch tick)
private readonly Dictionary<int, long> pendingPings = new();
private ConcurrentDictionary<int, long> pendingPings = new();
private int seqNumber;
private const int MAX_PENDING_PINGS = 1000;
// 유닛 테스트용 (0 = 제한 없음)
public int TestCount
{
get;
set;
} = 0;
// 통계
public int SentCount
@@ -48,11 +58,12 @@ 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();
manager = new NetManager(listener);
writer = new NetDataWriter();
listener.PeerConnectedEvent += netPeer =>
{
@@ -65,19 +76,25 @@ public class DummyClients
short code = reader.GetShort();
short bodyLength = reader.GetShort();
string? msg = reader.GetString();
long sentTick;
if (msg != null && msg.StartsWith("Echo seq:") &&
int.TryParse(msg.Substring("Echo seq:".Length), out int seq) &&
pendingPings.TryGetValue(seq, out long sentTick))
pendingPings.TryRemove(seq, out sentTick))
{
double rttMs = (Stopwatch.GetTimestamp() - sentTick) * 1000.0 / Stopwatch.Frequency;
LastRttMs = rttMs;
TotalRttMs += rttMs;
RttCount++;
pendingPings.Remove(seq);
}
ReceivedCount++;
if (TestCount > 0 && ReceivedCount >= TestCount)
{
peer.Disconnect();
}
reader.Recycle();
};
@@ -93,7 +110,7 @@ public class DummyClients
public void SendPing()
{
if (peer == null)
if (peer == null || writer == null)
{
return;
}
@@ -101,15 +118,29 @@ public class DummyClients
int seq = seqNumber++;
pendingPings[seq] = Stopwatch.GetTimestamp();
NetDataWriter writer = new NetDataWriter();
// 응답 없는 오래된 ping 정리 (패킷 유실 시 메모리 누수 방지)
if (pendingPings.Count > MAX_PENDING_PINGS)
{
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 = $"seq:{seq}".Length;
packetHeader.BodyLength = (ushort)$"Echo seq:{seq}".Length;
writer.Put((short)packetHeader.Code);
writer.Put((short)packetHeader.BodyLength);
writer.Put($"Echo seq:{seq}");
peer.Send(writer, DeliveryMethod.ReliableOrdered);
// 순서보장 안함 HOL Blocking 제거
peer.Send(writer, DeliveryMethod.ReliableUnordered);
SentCount++;
writer.Reset();
}
public double AvgRttMs => RttCount > 0 ? TotalRttMs / RttCount : 0.0;

View File

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

View File

@@ -100,41 +100,23 @@ public class PlayerInfo
}
}
[ProtoContract]
public class ItemInfo
{
[ProtoMember(1)]
public int ItemId
{
get;
set;
}
[ProtoMember(2)]
public int Count
{
get;
set;
}
}
// ============================================================
// 인증
// ============================================================
// RECV_TOKEN
// ACC_TOKEN
[ProtoContract]
public class RecvTokenPacket
public class AccTokenPacket
{
[ProtoMember(1)]
public string Token
public long Token
{
get;
set;
}
}
// LOAD_GAME
// LOAD_GAME 내 정보
[ProtoContract]
public class LoadGamePacket
{
@@ -151,27 +133,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 +232,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 +487,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,56 @@
namespace ClientTester.Packet;
public enum PacketCode : short
public enum PacketCode : ushort
{
NONE,
// 초기 클라이언트 시작시 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

@@ -7,22 +7,24 @@ namespace ClientTester.Packet
public static class PacketSerializer
{
// 직렬화: 객체 → byte[]
public static byte[] Serialize<T>(ushort type, ushort size, T packet)
// 직렬화: 객체 → byte[] (size는 payload 크기로 자동 계산)
public static byte[] Serialize<T>(ushort type, T packet)
{
MemoryStream ms = new MemoryStream();
using MemoryStream payloadMs = new MemoryStream();
Serializer.Serialize(payloadMs, packet);
byte[] payload = payloadMs.ToArray();
ushort size = (ushort)payload.Length;
byte[] result = new byte[4 + payload.Length];
// 2바이트 패킷 타입 헤더
ms.WriteByte((byte)(type & 0xFF));
ms.WriteByte((byte)(type >> 8));
result[0] = (byte)(type & 0xFF);
result[1] = (byte)(type >> 8);
// 2바이트 패킷 길이 헤더
ms.WriteByte((byte)(size & 0xFF));
ms.WriteByte((byte)(size >> 8));
result[2] = (byte)(size & 0xFF);
result[3] = (byte)(size >> 8);
// protobuf 페이로드
Serializer.Serialize(ms, packet);
return ms.ToArray();
Buffer.BlockCopy(payload, 0, result, 4, payload.Length);
return result;
}
// 역직렬화: byte[] → (PacketType, payload bytes)
@@ -34,19 +36,27 @@ namespace ClientTester.Packet
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);
// 헤더에 명시된 size와 실제 데이터 길이 검증
int actualPayloadLen = data.Length - 4;
if (size > actualPayloadLen)
{
Log.Warning("[PacketSerializer] 페이로드 크기 불일치 HeaderSize={Size} ActualSize={Actual}", size,
actualPayloadLen);
return (0, 0, null)!;
}
byte[] payload = new byte[size];
Buffer.BlockCopy(data, 4, payload, 0, size);
return (type, size, payload);
}
// 페이로드 → 특정 타입으로 역직렬화
public static T DeserializePayload<T>(byte[] payload)
{
MemoryStream ms = new MemoryStream(payload);
using MemoryStream ms = new MemoryStream(payload);
return Serializer.Deserialize<T>(ms);
}
}

View File

@@ -1,3 +1,4 @@
using ClientTester.DummyService;
using ClientTester.EchoDummyService;
using Serilog;
@@ -8,18 +9,10 @@ class EcoClientTester
public static readonly string CONNECTION_KEY = "test";
public static readonly int CLIENT_COUNT = 100;
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,11 +21,47 @@ class EcoClientTester
cts.Cancel();
};
DummyClientService service = new DummyClientService(CLIENT_COUNT, SERVER_IP, SERVER_PORT, CONNECTION_KEY, 100);
service.OnAllDisconnected += async () =>
EchoDummyClientService service =
new EchoDummyClientService(CLIENT_COUNT, SERVER_IP, SERVER_PORT, CONNECTION_KEY, 100);
service.OnAllDisconnected += () =>
{
Log.Warning("[SHUTDOWN] 종료 이벤트 발생, 종료 중...");
await cts.CancelAsync();
cts.Cancel();
};
// service.IsTest = true;
// service.TestCount = 100;
await service.RunAsync(cts.Token);
service.PrintStats();
service.Stop();
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);
@@ -42,4 +71,46 @@ class EcoClientTester
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,82 @@
using MMOserver.Game.Channel.Maps;
namespace MMOserver.Game.Channel;
public class Channel
{
// 로비
private Robby robby = new Robby();
// 채널 내 유저 상태 (hashKey → Player)
private Dictionary<long, Player> connectUsers = new Dictionary<long, Player>();
public int ChannelId
{
get;
private set;
}
public int UserCount
{
get;
private set;
}
public int UserCountMax
{
get;
private set;
} = 100;
public Channel(int channelId)
{
ChannelId = channelId;
}
public void AddUser(long userId, Player player)
{
connectUsers[userId] = player;
UserCount++;
}
public void RemoveUser(long userId)
{
connectUsers.Remove(userId);
UserCount--;
}
// 채널 내 모든 유저의 hashKey 반환
public IEnumerable<long> GetConnectUsers()
{
return connectUsers.Keys;
}
// 채널 내 모든 Player 반환
public IEnumerable<Player> GetPlayers()
{
return connectUsers.Values;
}
// 특정 유저의 Player 반환
public Player? GetPlayer(long userId)
{
connectUsers.TryGetValue(userId, out Player? player);
return player;
}
public int HasUser(long userId)
{
if (connectUsers.ContainsKey(userId))
{
return ChannelId;
}
return -1;
}
// 로비 가져옴
public Robby GetRobby()
{
return robby;
}
}

View File

@@ -0,0 +1,84 @@
namespace MMOserver.Game.Channel;
public class ChannelManager
{
// 일단은 채널은 서버 켤때 고정으로간다 1개
public static ChannelManager Instance
{
get;
} = new ChannelManager();
// 채널 관리
private List<Channel> channels = new List<Channel>();
// 채널별 유저 관리 (유저 key, 채널 val)
private Dictionary<long, int> connectUsers = new Dictionary<long, int>();
public ChannelManager()
{
Initializer();
}
public void Initializer(int channelSize = 1)
{
for (int i = 0; i < channelSize; i++)
{
channels.Add(new Channel(i));
}
}
public Channel GetChannel(int channelId)
{
return channels[channelId];
}
public List<Channel> GetChannels()
{
return channels;
}
public void AddUser(int channelId, long userId, Player player)
{
// 유저 추가
connectUsers[userId] = channelId;
// 채널에 유저 추가
channels[channelId].AddUser(userId, player);
}
public bool RemoveUser(long userId)
{
// 채널 있으면
int channelId = connectUsers[userId];
// 날린다.
if (channelId >= 0)
{
channels[channelId].RemoveUser(userId);
connectUsers.Remove(userId);
return true;
}
return false;
}
public int HasUser(long userId)
{
int channelId = -1;
if (connectUsers.ContainsKey(userId))
{
channelId = connectUsers[userId];
}
if (channelId != -1)
{
return channels[channelId].HasUser(userId);
}
return channelId;
}
public Dictionary<long, int> GetConnectUsers()
{
return connectUsers;
}
}

View File

@@ -0,0 +1,17 @@
using MMOserver.Game.Engine;
namespace MMOserver.Game.Channel.Maps;
public class Robby
{
// 마을 시작 지점 넣어 둔다.
public static Vector3 StartPosition
{
get;
set;
} = new Vector3(0, 0, 0);
public Robby()
{
}
}

View File

@@ -0,0 +1,36 @@
namespace MMOserver.Game.Engine;
public class Vector3
{
public int X
{
get;
set;
}
public int Y
{
get;
set;
}
public int Z
{
get;
set;
}
public Vector3()
{
X = 0;
Y = 0;
Z = 0;
}
public Vector3(int x, int y, int z)
{
X = x;
Y = y; // 수직 사실상 안쓰겠다.
Z = z;
}
}

View File

@@ -1,27 +1,303 @@
using LiteNetLib;
using LiteNetLib;
using MMOserver.Game.Channel;
using MMOserver.Packet;
using ProtoBuf;
using Serilog;
using ServerLib.Packet;
using ServerLib.Service;
namespace MMOserver.Game;
public class GameServer : ServerBase
{
private readonly Dictionary<ushort, Action<NetPeer, long, byte[]>> packetHandlers;
public GameServer(int port, string connectionString) : base(port, connectionString)
{
packetHandlers = new Dictionary<ushort, Action<NetPeer, long, byte[]>>
{
[(ushort)PacketCode.INTO_CHANNEL] = OnIntoChannel,
[(ushort)PacketCode.EXIT_CHANNEL] = OnExitChannel,
[(ushort)PacketCode.TRANSFORM_PLAYER] = OnTransformPlayer,
[(ushort)PacketCode.ACTION_PLAYER] = OnActionPlayer,
[(ushort)PacketCode.STATE_PLAYER] = OnStatePlayer,
};
}
protected override void OnSessionConnected(NetPeer peer, long hashKey)
{
throw new NotImplementedException();
Log.Information("[GameServer] 세션 연결 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
// 만약 wifi-lte 로 바꿔졌다 이때 이미 로비에 들어가 있다면 넘긴다.
ChannelManager cm = ChannelManager.Instance;
int channelId = cm.HasUser(hashKey);
if (channelId >= 0)
{
// 재연결: 채널 유저 목록 전송 (채널 선택 스킵, 바로 마을로)
SendIntoChannelPacket(peer, hashKey);
}
else
{
// 모든 채널 정보 던진다
SendLoadChannelPacket(peer, hashKey);
}
}
protected override void OnSessionDisconnected(NetPeer peer, long hashKey, DisconnectInfo info)
{
throw new NotImplementedException();
ChannelManager cm = ChannelManager.Instance;
if (cm.RemoveUser(hashKey))
{
Log.Information("[GameServer] 세션 해제 HashKey={Key} Reason={Reason}", hashKey, info.Reason);
}
}
protected override void HandlePacket(NetPeer peer, long hashKey, ushort type, byte[] payload)
{
throw new NotImplementedException();
if (packetHandlers.TryGetValue(type, out Action<NetPeer, long, byte[]>? handler))
{
handler(peer, hashKey, payload);
}
else
{
Log.Warning("[GameServer] 알 수 없는 패킷 Type={Type}", type);
}
}
// ============================================================
// 보내는 패킷
// ============================================================
private void SendLoadChannelPacket(NetPeer peer, long hashKey)
{
LoadChannelPacket loadChannelPacket = new LoadChannelPacket();
foreach (Channel.Channel channel in ChannelManager.Instance.GetChannels())
{
ChannelInfo info = new ChannelInfo();
info.ChannelId = channel.ChannelId;
info.ChannelUserConut = channel.UserCount;
info.ChannelUserMax = channel.UserCountMax;
loadChannelPacket.Channels.Add(info);
}
byte[] data = PacketSerializer.Serialize<LoadChannelPacket>((ushort)PacketCode.LOAD_CHANNEL, loadChannelPacket);
SendTo(peer, data);
}
// 나간 유저를 같은 채널 유저들에게 알림 (UPDATE_CHANNEL_USER IsAdd=false)
private void SendExitChannelPacket(NetPeer peer, long hashKey, int channelId, Player player)
{
UpdateChannelUserPacket packet = new UpdateChannelUserPacket
{
Players = ToPlayerInfo(player),
IsAdd = false
};
byte[] data = PacketSerializer.Serialize<UpdateChannelUserPacket>((ushort)PacketCode.UPDATE_CHANNEL_USER, packet);
// 이미 채널에서 제거된 후라 나간 본인에게는 전송되지 않음
BroadcastToChannel(channelId, data);
}
// 채널 입장 시 패킷 전송
// - 새 유저에게 : 기존 채널 유저 목록 (INTO_CHANNEL)
// - 기존 유저들에게 : 새 유저 입장 알림 (UPDATE_CHANNEL_USER IsAdd=true)
private void SendIntoChannelPacket(NetPeer peer, long hashKey)
{
ChannelManager cm = ChannelManager.Instance;
int channelId = cm.HasUser(hashKey);
if (channelId < 0)
{
return;
}
Channel.Channel channel = cm.GetChannel(channelId);
Player? myPlayer = channel.GetPlayer(hashKey);
// 1. 새 유저에게: 자신을 제외한 기존 채널 유저 목록 전송
IntoChannelPacket response = new IntoChannelPacket { ChannelId = channelId };
foreach (long userId in channel.GetConnectUsers())
{
if (userId == hashKey)
{
continue;
}
Player? p = channel.GetPlayer(userId);
if (p != null)
{
response.Players.Add(ToPlayerInfo(p));
}
}
byte[] toNewUser = PacketSerializer.Serialize<IntoChannelPacket>((ushort)PacketCode.INTO_CHANNEL, response);
SendTo(peer, toNewUser);
// 2. 기존 유저들에게: 새 유저 입장 알림
if (myPlayer != null)
{
UpdateChannelUserPacket notify = new UpdateChannelUserPacket
{
Players = ToPlayerInfo(myPlayer),
IsAdd = true
};
byte[] toOthers = PacketSerializer.Serialize<UpdateChannelUserPacket>((ushort)PacketCode.UPDATE_CHANNEL_USER, notify);
BroadcastToChannel(channelId, toOthers, peer);
}
}
// ============================================================
// 채널 브로드캐스트 헬퍼
// ============================================================
// 특정 채널의 모든 유저에게 전송 (exclude 지정 시 해당 피어 제외)
private void BroadcastToChannel(int channelId, byte[] data, NetPeer? exclude = null)
{
Channel.Channel channel = ChannelManager.Instance.GetChannel(channelId);
foreach (long userId in channel.GetConnectUsers())
{
if (!sessions.TryGetValue(userId, out NetPeer? targetPeer))
{
continue;
}
if (exclude != null && targetPeer.Id == exclude.Id)
{
continue;
}
SendTo(targetPeer, data);
}
}
// ============================================================
// Player ↔ PlayerInfo 변환 (패킷 전송 시에만 사용)
// ============================================================
private static PlayerInfo ToPlayerInfo(Player player)
{
return new PlayerInfo
{
PlayerId = player.PlayerId,
Nickname = player.Nickname,
Level = player.Level,
Hp = player.Hp,
MaxHp = player.MaxHp,
Mp = player.Mp,
MaxMp = player.MaxMp,
Position = new Vector3 { X = player.PosX, Y = player.PosY, Z = player.PosZ },
RotY = player.RotY,
};
}
// ============================================================
// 패킷 핸들러
// ============================================================
private void OnIntoChannel(NetPeer peer, long hashKey, byte[] payload)
{
IntoChannelPacket packet = Serializer.Deserialize<IntoChannelPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
// TODO: 실제 서비스에서는 DB/세션에서 플레이어 정보 로드 필요
Player newPlayer = new Player
{
HashKey = hashKey,
PlayerId = (int)(hashKey & 0x7FFFFFFF),
};
cm.AddUser(packet.ChannelId, hashKey, newPlayer);
Log.Debug("[GameServer] INTO_CHANNEL HashKey={Key} ChannelId={ChannelId}", hashKey, packet.ChannelId);
// 접속된 모든 유저 정보 전달
SendIntoChannelPacket(peer, hashKey);
}
private void OnExitChannel(NetPeer peer, long hashKey, byte[] payload)
{
ExitChannelPacket packet = Serializer.Deserialize<ExitChannelPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
// 제거 전에 채널/플레이어 정보 저장 (브로드캐스트에 필요)
int channelId = cm.HasUser(hashKey);
Player? player = channelId >= 0 ? cm.GetChannel(channelId).GetPlayer(hashKey) : null;
cm.RemoveUser(hashKey);
Log.Debug("[GameServer] EXIT_CHANNEL HashKey={Key} PlayerId={PlayerId}", hashKey, packet.PlayerId);
// 같은 채널 유저들에게 나갔다고 알림
if (channelId >= 0 && player != null)
{
SendExitChannelPacket(peer, hashKey, channelId, player);
}
}
private void OnTransformPlayer(NetPeer peer, long hashKey, byte[] payload)
{
TransformPlayerPacket packet = Serializer.Deserialize<TransformPlayerPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
int channelId = cm.HasUser(hashKey);
if (channelId < 0)
{
return;
}
// 채널 내 플레이어 위치/방향 상태 갱신
Player? player = cm.GetChannel(channelId).GetPlayer(hashKey);
if (player != null)
{
player.PosX = packet.Position.X;
player.PosY = packet.Position.Y;
player.PosZ = packet.Position.Z;
player.RotY = packet.RotY;
}
// 같은 채널 유저들에게 위치/방향 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize<TransformPlayerPacket>((ushort)PacketCode.TRANSFORM_PLAYER, packet);
BroadcastToChannel(channelId, data, peer);
}
private void OnActionPlayer(NetPeer peer, long hashKey, byte[] payload)
{
ActionPlayerPacket packet = Serializer.Deserialize<ActionPlayerPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
int channelId = cm.HasUser(hashKey);
if (channelId < 0)
{
return;
}
// 같은 채널 유저들에게 행동 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize<ActionPlayerPacket>((ushort)PacketCode.ACTION_PLAYER, packet);
BroadcastToChannel(channelId, data, peer);
}
private void OnStatePlayer(NetPeer peer, long hashKey, byte[] payload)
{
StatePlayerPacket packet = Serializer.Deserialize<StatePlayerPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
int channelId = cm.HasUser(hashKey);
if (channelId < 0)
{
return;
}
// 채널 내 플레이어 HP/MP 상태 갱신
Player? player = cm.GetChannel(channelId).GetPlayer(hashKey);
if (player != null)
{
player.Hp = packet.Hp;
player.MaxHp = packet.MaxHp;
player.Mp = packet.Mp;
player.MaxMp = packet.MaxMp;
}
// 같은 채널 유저들에게 스테이트 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize<StatePlayerPacket>((ushort)PacketCode.STATE_PLAYER, packet);
BroadcastToChannel(channelId, data, peer);
}
}

View File

@@ -0,0 +1,77 @@
namespace MMOserver.Game;
public class Player
{
public long HashKey
{
get;
set;
}
public int PlayerId
{
get;
set;
}
public string Nickname
{
get;
set;
} = string.Empty;
public int Level
{
get;
set;
}
public int Hp
{
get;
set;
}
public int MaxHp
{
get;
set;
}
public int Mp
{
get;
set;
}
public int MaxMp
{
get;
set;
}
// 위치/방향 (클라이언트 패킷과 동일하게 float)
public float PosX
{
get;
set;
}
public float PosY
{
get;
set;
}
public float PosZ
{
get;
set;
}
public float RotY
{
get;
set;
}
}

View File

@@ -100,24 +100,6 @@ public class PlayerInfo
}
}
[ProtoContract]
public class ItemInfo
{
[ProtoMember(1)]
public int ItemId
{
get;
set;
}
[ProtoMember(2)]
public int Count
{
get;
set;
}
}
// ============================================================
// 인증
// ============================================================
@@ -134,7 +116,7 @@ public class RecvTokenPacket
}
}
// LOAD_GAME
// LOAD_GAME 내 정보
[ProtoContract]
public class LoadGamePacket
{
@@ -151,27 +133,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;
} = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록
}
// UPDATE_CHANNEL_USER 유저 접속/나감
[ProtoContract]
public class UpdateChannelUserPacket
{
[ProtoMember(1)]
public PlayerInfo Players
{
get;
set;
}
[ProtoMember(2)]
public bool IsAdd
{
get;
set;
}
}
// EXIT_LOBBY
// EXIT_CHANNEL 나가는 유저
[ProtoContract]
public class ExitLobbyPacket
public class ExitChannelPacket
{
[ProtoMember(1)]
public int PlayerId
@@ -181,174 +232,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 +487,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,56 @@
namespace MMOserver.Packet;
public enum PacketCode : short
public enum PacketCode : ushort
{
NONE,
// 초기 클라이언트 시작시 jwt토큰 받아옴
RECV_TOKEN,
// jwt토큰 검증후 게임에 들어갈지 말지 (내 데이터도 전송)
// 내 정보 로드 (서버 -> 클라)
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

@@ -7,7 +7,7 @@ namespace MMOserver;
class Program
{
private static void Main()
private static async Task Main()
{
// .MinimumLevel.Warning() // Warning 이상만 출력 배포시
@@ -43,17 +43,24 @@ class Program
};
// 게임 서버 스레드 생성
Thread serverThread = new Thread(() =>
{
gameServer.Init();
gameServer.Run();
});
// Thread serverThread = new Thread(() =>
// {
// gameServer.Init();
// gameServer.Run();
// });
// 게임 서버 스레드 시작
serverThread.Start();
// serverThread.Start();
// Run()이 끝날 때까지 대기
serverThread.Join();
// serverThread.Join();
// 비동기 변경
await Task.Run(async () =>
{
gameServer.Init();
await gameServer.Run();
});
// Log 종료
Log.CloseAndFlush();

View File

@@ -11,38 +11,80 @@ public class TestHandler
public TestHandler(TestService testService) => _testService = testService;
public async Task<string> GetTestAsync(int id)
{
try
{
Test? result = await _testService.GetTestAsync(id);
return result is null
? HandlerHelper.Error("Test not found")
: HandlerHelper.Success(result);
}
catch (Exception ex)
{
return HandlerHelper.Error(ex.Message);
}
}
public async Task<string> GetTestByUuidAsync(string uuid)
{
try
{
Test? result = await _testService.GetTestByUuidAsync(uuid);
return result is null
? HandlerHelper.Error("Test not found")
: HandlerHelper.Success(result);
}
catch (Exception ex)
{
return HandlerHelper.Error(ex.Message);
}
}
public async Task<string> GetAllTestsAsync()
{
try
{
return HandlerHelper.Success(await _testService.GetAllTestsAsync());
}
catch (Exception ex)
{
return HandlerHelper.Error(ex.Message);
}
}
public async Task<string> CreateTestAsync(int testA, string testB, double testC)
{
try
{
return HandlerHelper.Success(await _testService.CreateTestAsync(testA, testB, testC));
}
catch (Exception ex)
{
return HandlerHelper.Error(ex.Message);
}
}
public async Task<string> UpdateTestAsync(int id, int? testA, string? testB, double? testC)
{
try
{
return HandlerHelper.Success(await _testService.UpdateTestAsync(id, testA, testB, testC));
}
catch (Exception ex)
{
return HandlerHelper.Error(ex.Message);
}
}
public async Task<string> DeleteTestAsync(int id)
{
try
{
return HandlerHelper.Success(await _testService.DeleteTestAsync(id));
}
catch (Exception ex)
{
return HandlerHelper.Error(ex.Message);
}
}
}

View File

@@ -7,7 +7,7 @@ namespace MMOserver.RDB.Repositories;
// 실제 호출할 쿼리들
public class TestRepository : ARepository<Test>
{
public TestRepository(DbConnectionFactory factory) : base(factory)
public TestRepository(IDbConnectionFactory factory) : base(factory)
{
}

View File

@@ -9,22 +9,24 @@ namespace ServerLib.Packet
public static class PacketSerializer
{
// 직렬화: 객체 → byte[]
public static byte[] Serialize<T>(ushort type, ushort size, T packet)
// 직렬화: 객체 → byte[] (size는 payload 크기로 자동 계산)
public static byte[] Serialize<T>(ushort type, T packet)
{
MemoryStream ms = new MemoryStream();
using MemoryStream payloadMs = new MemoryStream();
Serializer.Serialize(payloadMs, packet);
byte[] payload = payloadMs.ToArray();
ushort size = (ushort)payload.Length;
byte[] result = new byte[4 + payload.Length];
// 2바이트 패킷 타입 헤더
ms.WriteByte((byte)(type & 0xFF));
ms.WriteByte((byte)(type >> 8));
result[0] = (byte)(type & 0xFF);
result[1] = (byte)(type >> 8);
// 2바이트 패킷 길이 헤더
ms.WriteByte((byte)(size & 0xFF));
ms.WriteByte((byte)(size >> 8));
result[2] = (byte)(size & 0xFF);
result[3] = (byte)(size >> 8);
// protobuf 페이로드
Serializer.Serialize(ms, packet);
return ms.ToArray();
Buffer.BlockCopy(payload, 0, result, 4, payload.Length);
return result;
}
// 역직렬화: byte[] → (PacketType, payload bytes)
@@ -36,19 +38,26 @@ namespace ServerLib.Packet
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);
// 헤더에 명시된 size와 실제 데이터 길이 검증
int actualPayloadLen = data.Length - 4;
if (size > actualPayloadLen)
{
Log.Warning("[PacketSerializer] 페이로드 크기 불일치 HeaderSize={Size} ActualSize={Actual}", size, actualPayloadLen);
return (0, 0, null)!;
}
byte[] payload = new byte[size];
Buffer.BlockCopy(data, 4, payload, 0, size);
return (type, size, payload);
}
// 페이로드 → 특정 타입으로 역직렬화
public static T DeserializePayload<T>(byte[] payload)
{
MemoryStream ms = new MemoryStream(payload);
using MemoryStream ms = new MemoryStream(payload);
return Serializer.Deserialize<T>(ms);
}
}

View File

@@ -22,59 +22,59 @@ public abstract class ARepository<T> where T : class
// Dapper.Contrib 기본 CRUD
public async Task<T?> GetByIdAsync(int id)
{
IDbConnection conn = CreateConnection();
using IDbConnection conn = CreateConnection();
return await conn.GetAsync<T>(id);
}
public async Task<IEnumerable<T>> GetAllAsync()
{
IDbConnection conn = CreateConnection();
using IDbConnection conn = CreateConnection();
return await conn.GetAllAsync<T>();
}
public async Task<long> InsertAsync(T entity)
{
IDbConnection conn = CreateConnection();
using IDbConnection conn = CreateConnection();
return await conn.InsertAsync(entity);
}
public async Task<bool> UpdateAsync(T entity)
{
IDbConnection conn = CreateConnection();
using IDbConnection conn = CreateConnection();
return await conn.UpdateAsync(entity);
}
public async Task<bool> DeleteAsync(T entity)
{
IDbConnection conn = CreateConnection();
using IDbConnection conn = CreateConnection();
return await conn.DeleteAsync(entity);
}
// 커스텀 쿼리 헬퍼 (복잡한 쿼리용)
protected async Task<IEnumerable<T>> QueryAsync(string sql, object? param = null)
{
IDbConnection conn = CreateConnection();
using IDbConnection conn = CreateConnection();
return await conn.QueryAsync<T>(sql, param);
}
protected async Task<T?> QueryFirstOrDefaultAsync(string sql, object? param = null)
{
IDbConnection conn = CreateConnection();
using IDbConnection conn = CreateConnection();
return await conn.QueryFirstOrDefaultAsync<T>(sql, param);
}
protected async Task<int> ExecuteAsync(string sql, object? param = null)
{
IDbConnection conn = CreateConnection();
using IDbConnection conn = CreateConnection();
return await conn.ExecuteAsync(sql, param);
}
// 트랜잭션 헬퍼
protected async Task<TResult> WithTransactionAsync<TResult>(Func<IDbConnection, IDbTransaction, Task<TResult>> action)
{
IDbConnection conn = CreateConnection();
using IDbConnection conn = CreateConnection();
conn.Open();
IDbTransaction tx = conn.BeginTransaction();
using IDbTransaction tx = conn.BeginTransaction();
try
{
TResult result = await action(conn, tx);

View File

@@ -34,15 +34,29 @@ public abstract class ServerBase : INetEventListener
// 인증된 세션 (hashKey → NetPeer) 재연결 조회용
// peer → hashKey 역방향은 peer.Tag as Session 으로 대체
private readonly Dictionary<long, NetPeer> sessions = new();
protected readonly Dictionary<long, NetPeer> sessions = new();
// 재사용 NetDataWriter (단일 스레드 폴링이므로 안전)
private readonly NetDataWriter cachedWriter = new();
// 핑 로그 출력 여부
public bool PingLogRtt { get; set; }
public bool PingLogRtt
{
get;
set;
}
public int Port { get; }
public string ConnectionString { get; }
public int Port
{
get;
}
private bool isListening = false;
public string ConnectionString
{
get;
}
private volatile bool isListening = false;
public ServerBase(int port, string connectionString)
{
@@ -61,7 +75,7 @@ public abstract class ServerBase : INetEventListener
isListening = true;
}
public virtual void Run()
public async Task Run()
{
netManager.Start(Port);
Log.Information("[Server] 시작 Port={Port}", Port);
@@ -69,8 +83,9 @@ public abstract class ServerBase : INetEventListener
while (isListening)
{
netManager.PollEvents();
Thread.Sleep(15);
await Task.Delay(1);
}
netManager.Stop();
Log.Information("[Server] 종료 Port={Port}", Port);
}
@@ -86,7 +101,7 @@ public abstract class ServerBase : INetEventListener
// 벤 기능 추가? 한국 ip만?
if (request.AcceptIfKey(ConnectionString) == null)
{
Log.Debug("해당 클라이언트의 ConnectionKey={request.ConnectionKey}가 동일하지 않습니다", request.Data.ToString());
Log.Debug("해당 클라이언트의 ConnectionKey가 동일하지 않습니다. Data={Data}", request.Data.ToString());
}
}
@@ -112,6 +127,7 @@ public abstract class ServerBase : INetEventListener
Log.Information("[Server] 세션 해제 HashKey={Key} Reason={Reason}", session.HashKey, disconnectInfo.Reason);
OnSessionDisconnected(peer, session.HashKey, disconnectInfo);
}
peer.Tag = null;
}
}
@@ -125,6 +141,13 @@ public abstract class ServerBase : INetEventListener
{
(ushort type, ushort size, byte[] payload) = PacketSerializer.Deserialize(data);
// Deserialize 실패 시 payload가 null
if (payload == null)
{
Log.Warning("[Server] 패킷 역직렬화 실패 PeerId={Id} DataLen={Len}", peer.Id, data.Length);
return;
}
// 0이라면 에코 서버 테스트용 따로 처리
if (type == 0)
{
@@ -181,31 +204,31 @@ public abstract class ServerBase : INetEventListener
private void HandleEcho(NetPeer peer, byte[] payload)
{
// if (payload.Length < sizeof(long))
// {
// Log.Warning("[Server] Echo 페이로드 크기 오류 PeerId={Id}", peer.Id);
// peer.Disconnect();
// return;
// }
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();
Log.Debug("[Echo] : addr={Addr}, str={Str}", peer.Address, reader.GetString());
SendTo(peer, payload);
// Echo메시지는 순서보장 안함 HOL Blocking 제거
SendTo(peer, payload, DeliveryMethod.ReliableUnordered);
}
// ─── Auth 처리 (내부) ────────────────────────────────────────────────
private void HandleAuth(NetPeer peer, byte[] payload)
{
// if (payload.Length < sizeof(long))
// {
// Log.Warning("[Server] Auth 페이로드 크기 오류 PeerId={Id}", peer.Id);
// peer.Disconnect();
// return;
// }
if (payload.Length < sizeof(long))
{
Log.Warning("[Server] Auth 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
peer.Disconnect();
return;
}
long hashKey = BitConverter.ToInt64(payload, 0);
@@ -228,31 +251,28 @@ public abstract class ServerBase : INetEventListener
// ─── 전송 헬퍼 ───────────────────────────────────────────────────────
// NetDataWriter writer 풀처리 필요할듯
// peer에게 전송
protected void SendTo(NetPeer peer, byte[] data, DeliveryMethod method = DeliveryMethod.ReliableOrdered)
{
NetDataWriter writer = new NetDataWriter();
writer.Put(data);
peer.Send(writer, method);
cachedWriter.Reset();
cachedWriter.Put(data);
peer.Send(cachedWriter, method);
}
// 모두에게 전송
protected void Broadcast(byte[] data, DeliveryMethod method = DeliveryMethod.ReliableOrdered)
{
// 일단 channelNumber는 건드리지 않는다
NetDataWriter writer = new NetDataWriter();
writer.Put(data);
netManager.SendToAll(writer, 0, method);
cachedWriter.Reset();
cachedWriter.Put(data);
netManager.SendToAll(cachedWriter, 0, method);
}
// exclude 1개 제외 / 나 제외 정도
protected void BroadcastExcept(byte[] data, NetPeer exclude, DeliveryMethod method = DeliveryMethod.ReliableOrdered)
{
// 일단 channelNumber는 건드리지 않는다
NetDataWriter writer = new NetDataWriter();
writer.Put(data);
netManager.SendToAll(writer, 0, method, exclude);
cachedWriter.Reset();
cachedWriter.Put(data);
netManager.SendToAll(cachedWriter, 0, method, exclude);
}
// ─── 서브클래스 구현 ─────────────────────────────────────────────────