39 Commits

Author SHA1 Message Date
53eabe2f3d fix: MMO 서버 버그 수정 및 안정성 개선 (20건)
- VerifyTokenAsync 인증 우회 차단 (빈 문자열→null 반환)
- HandleAuth/OnIntoBossRaid async void→async Task 전환
- await 후 스레드 안전성 확보 (sessionLock 도입)
- 보스레이드 파티원 세션/토큰 개별 전달 (tokens Dictionary 타입 수정)
- 409 Conflict 처리 추가, bossId 하드코딩 제거
- 채널 이동 시 레이드 맵 해제, 플레이어 상태 보존
- 파티원 닉네임 손실 수정, HandlePartyLeaveOnExit 알림 타입 수정
- PacketCode enum 명시적 값 할당, MaplId→MapId/BossRaidAccesss→Access 오타 수정
- Channel.UserCount 음수 방지, HandleAuth 재연결 로직 수정

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 23:26:39 +09:00
7f2cd281da fix: MMO 서버 로직 버그 6건 수정
1. PlayerId 스푸핑 방지: OnTransformPlayer, OnActionPlayer, OnStatePlayer에서
   브로드캐스트 전 packet.PlayerId = hashKey로 강제 교체

2. HP/MP 클라이언트 조작 방지: OnStatePlayer에서 범위 클램핑
   (0 ≤ Hp ≤ MaxHp, 0 ≤ Mp ≤ MaxMp)

3. CreateParty 파티원 등록 누락 수정:
   - memberIds 파라미터 사용 시 모든 멤버를 playerPartyMap에 등록
   - 리더 중복 추가 방지 (Contains 체크)

4. OnIntoChannel 채널 만석 유령 상태 방지:
   이전 채널 제거 후 새 채널 입장 실패 시 이전 채널로 복귀

5. HandleAuth async 경합 방지:
   authenticatingTokens HashSet으로 동일 토큰 동시 인증 차단

6. 레이드 맵 미반환 수정:
   TryReleaseRaidMap 헬퍼 추가, OnChangeMap/OnSessionDisconnected에서
   레이드 맵(1001+) 유저 0명 시 인스턴스 맵 해제

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 00:34:40 +09:00
qornwh1
39ef81d48a fix : 일단 메시지body 임시 처리 (hp, 경험치, 파워 등) 2026-03-16 20:47:22 +09:00
qornwh1
6faab45ecc feat : 레이드 이동 메시지 수정 모두에게 2026-03-16 20:36:24 +09:00
qornwh1
dd8dcc58d2 feat : 보스레이드 신청 메시지 응답 패킷 구현 2026-03-16 19:19:59 +09:00
qornwh1
f6b378cad7 feat : 보스 레이드 입장 메시지 기능 추가 2026-03-16 17:55:08 +09:00
qornwh1
943302c2f1 fix : 맵 이동시 유저 진입 동기화버그 수정 2026-03-16 16:07:49 +09:00
qornwh1
523247c9b1 fea : Map단위로 캐릭터 이동 메시지 전달기능 추가 2026-03-16 15:16:42 +09:00
qornwh1
e4429177db feat : 맵관리 코드 추가 작업 2026-03-16 14:50:29 +09:00
qornwh1
f564199cb5 fix : 변수 네이밍 수정 2026-03-16 11:27:07 +09:00
qornwh1
f2bc3d7924 fix : 서버 설정파일 빼기 작업 2026-03-16 11:14:38 +09:00
qornwh1
f6067047d9 fix : 토큰인증 스펙 수정 2026-03-16 10:43:30 +09:00
qornwh1
2bc01f9c18 fix : 토큰 인증 수정 2026-03-16 10:22:00 +09:00
qornwh1
3d62cbf58d feat : Vector3 int -> float, 이동시 int 캐스팅 제거, 프로그램 실행시 setting.json 추가 2026-03-12 16:49:23 +09:00
qornwh1
d626a7156d feat : 보스 채널은 안띄운다. 2026-03-12 16:09:13 +09:00
qornwh1
0ebe269146 feat : 보스전 채널 생성, 파티 함께 채널 이동 구현 2026-03-12 13:23:30 +09:00
qornwh1
4956a2e26d 도커 파일 포트 접속 추가 2026-03-11 19:45:50 +09:00
qornwh1
6e8a9c0b5e feat : 파티용 패킷 수정,
파티 CRUD 버그 수정
2026-03-11 19:36:00 +09:00
qornwh1
056ec8d0c3 feat : 파티 정보 업데이트 기능 추가 2026-03-11 15:09:06 +09:00
qornwh1
1487082cc6 fix : 도커 의존성 추가, 윈도우용 미니덤프 제거 Dotnet-dump사용 2026-03-11 12:55:24 +09:00
qornwh1
9828b967a1 feat : 파티 패킷 추가 / 채널 접속시 모든 파티 리스트 전달 2026-03-10 09:40:00 +09:00
qornwh1
a3bcbd073e fix : 덤프 남길때 현재 콜스택 저장 기능 추가 2026-03-10 09:03:46 +09:00
qornwh1
275d09001b feat : 0번 채널은 스킵 2026-03-09 16:17:38 +09:00
qornwh1
f8ebfc7281 feat : 클라쪽도 채팅 패킷, 오타 수정 2026-03-09 08:55:03 +09:00
qornwh1
de4e344cdb feat : 채팅 기증 추가, 귓속말은 대상이 id라는 문제 있음 <= 현재는 그대로 둔다 2026-03-09 08:51:50 +09:00
qornwh1
5df664e05b fix : 패킷 Vector3 -> Position 변경 (유니티 호환성) 2026-03-08 23:46:34 +09:00
qornwh1
3188dbeb3d feat : 서버 실패 코드 메시지 기능 추가 2026-03-08 22:03:06 +09:00
qornwh1
06741f2a55 feat : 파티매니저 채널에 종속되도록 변경 2026-03-08 22:01:55 +09:00
qornwh1
a53d838e24 feat : 파티 구조 뼈대 완성 2026-03-08 21:48:34 +09:00
qornwh1
a5d3b48707 feat : 파티 요청 메시지 추가 2026-03-08 21:00:24 +09:00
qornwh1
5165b9e6dc fix : playerID == hashkey 통일 / long => int로 변경 2026-03-08 20:47:23 +09:00
qornwh1
1b7f0003fb feat : 파티 패킷 구조 1개로 통일(CRUD) 2026-03-08 20:13:07 +09:00
qornwh1
76c6f46bbe feat : UuidGenerator 여러곳에서 사용하도록 싱글톤 제거 2026-03-08 17:47:49 +09:00
qornwh1
aed5d7d0b6 feat: 싱글톤 제네릭 변경 2026-03-08 17:42:12 +09:00
qornwh1
b4ad85e452 fix : 닉네임 hashkey로 임시 대체 2026-03-06 17:11:44 +09:00
qornwh1
d36de75534 feat : 채널 접속시 내 정보도 전달 2026-03-06 16:10:35 +09:00
qornwh1
1285284aa1 fix : 더미클라이언트 플레이어 정보 누락 수정 2026-03-06 15:07:00 +09:00
qornwh1
2a7d4aeb09 feat : 서버 로직 성능개선 / 결과 정리 2026-03-06 10:16:36 +09:00
qornwh1
85c3276207 feat : 세션 끊길때 같은 채널에 나가는 메시지 보냄 2026-03-05 17:04:50 +09:00
34 changed files with 2616 additions and 397 deletions

View File

@@ -12,7 +12,7 @@ public class DummyClients
private EventBasedNetListener listener; private EventBasedNetListener listener;
private NetDataWriter? writer; private NetDataWriter? writer;
public NetPeer? peer; public NetPeer? peer;
public long clientId; // 일단 이게 hashKey가 됨 => 0 ~ 1000번까지는 더미용응로 뺴둠 public int clientId; // 일단 이게 hashKey가 됨 => 0 ~ 1000번까지는 더미용응로 뺴둠
// info // info
private Vector3 position = new Vector3(); private Vector3 position = new Vector3();
@@ -50,7 +50,7 @@ public class DummyClients
get; get;
} }
public DummyClients(long clientId, string ip, int port, string key) public DummyClients(int clientId, string ip, int port, string key)
{ {
this.clientId = clientId; this.clientId = clientId;
listener = new EventBasedNetListener(); listener = new EventBasedNetListener();
@@ -125,8 +125,8 @@ public class DummyClients
distance = hitWall ? 0f : distance - step; distance = hitWall ? 0f : distance - step;
// 정수 Vector3 갱신 // 정수 Vector3 갱신
position.X = (int)MathF.Round(posX); position.X = posX;
position.Z = (int)MathF.Round(posZ); position.Z = posZ;
} }
public void SendTransform() public void SendTransform()
@@ -139,12 +139,12 @@ public class DummyClients
UpdateDummy(); UpdateDummy();
TransformPlayerPacket transformPlayerPacket = new TransformPlayerPacket TransformPlayerPacket transformPlayerPacket = new TransformPlayerPacket
{ {
PlayerId = (int)clientId, PlayerId = clientId,
RotY = rotY, RotY = rotY,
Position = new Packet.Vector3 Position = new Packet.Position
{ {
X = position.X, X = position.X,
Y = 0, // 높이는 버린다. Y = -0.5f, // 높이는 버린다.
Z = position.Z Z = position.Z
} }
}; };

View File

@@ -8,6 +8,12 @@
<RootNamespace>ClientTester</RootNamespace> <RootNamespace>ClientTester</RootNamespace>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="LiteNetLib" Version="2.0.2" /> <PackageReference Include="LiteNetLib" Version="2.0.2" />
<PackageReference Include="protobuf-net" Version="3.2.56" /> <PackageReference Include="protobuf-net" Version="3.2.56" />

View File

@@ -25,7 +25,7 @@ public class EchoPacket
// ============================================================ // ============================================================
[ProtoContract] [ProtoContract]
public class Vector3 public class Position
{ {
[ProtoMember(1)] [ProtoMember(1)]
public float X public float X
@@ -102,7 +102,7 @@ public class PlayerInfo
} }
[ProtoMember(8)] [ProtoMember(8)]
public Vector3 Position public Position Position
{ {
get; get;
set; set;
@@ -125,7 +125,7 @@ public class PlayerInfo
public class DummyAccTokenPacket public class DummyAccTokenPacket
{ {
[ProtoMember(1)] [ProtoMember(1)]
public long Token public int Token
{ {
get; get;
set; set;
@@ -185,7 +185,7 @@ public class ChannelInfo
} }
[ProtoMember(2)] [ProtoMember(2)]
public int ChannelUserConut public int ChannelUserCount
{ {
get; get;
set; set;
@@ -210,7 +210,42 @@ public class LoadChannelPacket
} = new List<ChannelInfo>(); } = new List<ChannelInfo>();
} }
// INTO_CHANNEL 클라->서버: 입장할 채널 ID / 서버->클라: 채널 내 나 이외 플레이어 목록 // 채널 내 파티 정보 (INTO_CHANNEL 응답에 포함)
[ProtoContract]
public class PartyInfoData
{
[ProtoMember(1)]
public int PartyId
{
get;
set;
}
[ProtoMember(2)]
public int LeaderId
{
get;
set;
}
[ProtoMember(3)]
public List<int> MemberPlayerIds
{
get;
set;
} = new List<int>();
[ProtoMember(4)]
public string PartyName
{
get;
set;
}
}
// INTO_CHANNEL
// 클라->서버: 입장할 채널 ID
// 서버->클라: 채널 내 나 이외 플레이어 목록
[ProtoContract] [ProtoContract]
public class IntoChannelPacket public class IntoChannelPacket
{ {
@@ -227,6 +262,47 @@ public class IntoChannelPacket
get; get;
set; set;
} = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록 } = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록
[ProtoMember(3)]
public List<PartyInfoData> Parties
{
get;
set;
} = new List<PartyInfoData>(); // 서버->클라: 채널 내 파티 목록
}
// 파티원 모두 채널이동
// 클라->서버: 입장할 채널 ID
[ProtoContract]
public class IntoChannelPartyPacket
{
[ProtoMember(1)]
public int ChannelId
{
get;
set;
} // 클라->서버: 입장할 채널 ID
[ProtoMember(2)]
public List<PlayerInfo> Players
{
get;
set;
} = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록
[ProtoMember(3)]
public List<PartyInfoData> Parties
{
get;
set;
} = new List<PartyInfoData>(); // 서버->클라: 채널 내 파티 목록
[ProtoMember(4)]
public int PartyId
{
get;
set;
}
} }
// UPDATE_CHANNEL_USER 유저 접속/나감 // UPDATE_CHANNEL_USER 유저 접속/나감
@@ -287,7 +363,7 @@ public class TransformPlayerPacket
} }
[ProtoMember(2)] [ProtoMember(2)]
public Vector3 Position public Position Position
{ {
get; get;
set; set;
@@ -399,7 +475,7 @@ public class TransformNpcPacket
} }
[ProtoMember(2)] [ProtoMember(2)]
public Vector3 Position public Position Position
{ {
get; get;
set; set;
@@ -516,6 +592,32 @@ public class DamagePacket
} }
} }
// ============================================================
// 에러
// ============================================================
public enum ErrorCode : int
{
// 파티 (10021~)
PARTY_ALREADY_IN_PARTY = 10021,
PARTY_JOIN_FAILED = 10022,
PARTY_NOT_IN_PARTY = 10023,
PARTY_DELETE_FAILED = 10024,
PARTY_UPDATE_FAILED = 10025,
}
// ERROR (서버 -> 클라)
[ProtoContract]
public class ErrorPacket
{
[ProtoMember(1)]
public ErrorCode Code
{
get;
set;
}
}
// ============================================================ // ============================================================
// 파티 // 파티
// ============================================================ // ============================================================
@@ -523,16 +625,96 @@ public class DamagePacket
public enum PartyUpdateType public enum PartyUpdateType
{ {
CREATE, CREATE,
DELETE DELETE,
}
public enum UserPartyUpdateType
{
JOIN, JOIN,
LEAVE LEAVE,
UPDATE
} }
// UPDATE_PARTY // REQUEST_PARTY (클라 -> 서버) - CREATE: PartyName 사용 / JOIN·LEAVE·DELETE: PartyId 사용
[ProtoContract]
public class RequestPartyPacket
{
[ProtoMember(1)]
public PartyUpdateType Type
{
get;
set;
}
[ProtoMember(2)]
public int PartyId
{
get;
set;
} // JOIN, LEAVE, DELETE 시 사용
[ProtoMember(3)]
public string PartyName
{
get;
set;
} // CREATE 시 사용
}
// ============================================================
// 채팅
// ============================================================
public enum ChatType
{
GLOBAL, // 전체 채널
PARTY, // 파티원
WHISPER // 귓말
}
// CHAT (클라 -> 서버 & 서버 -> 클라)
// 클라->서버: Type, TargetId(WHISPER 시), Message
// 서버->클라: Type, SenderId, SenderNickname, TargetId(WHISPER 시), Message
[ProtoContract]
public class ChatPacket
{
[ProtoMember(1)]
public ChatType Type
{
get;
set;
}
[ProtoMember(2)]
public int SenderId
{
get;
set;
} // 서버에서 채워줌
[ProtoMember(3)]
public string SenderNickname
{
get;
set;
} // 서버에서 채워줌
[ProtoMember(4)]
public int TargetId
{
get;
set;
} // WHISPER일 때 대상 PlayerId
[ProtoMember(5)]
public string Message
{
get;
set;
}
}
// ============================================================
// 파티
// ============================================================
// UPDATE_PARTY (서버 -> 클라) - 파티 생성/삭제: LeaderId 사용 / 파티원 추가/제거: PlayerId 사용
[ProtoContract] [ProtoContract]
public class UpdatePartyPacket public class UpdatePartyPacket
{ {
@@ -556,30 +738,18 @@ public class UpdatePartyPacket
get; get;
set; set;
} }
}
// UPDATE_USER_PARTY [ProtoMember(4)]
[ProtoContract]
public class UpdateUserPartyPacket
{
[ProtoMember(1)]
public int PartyId
{
get;
set;
}
[ProtoMember(2)]
public int PlayerId public int PlayerId
{ {
get; get;
set; set;
} }
[ProtoMember(3)] [ProtoMember(5)]
public UserPartyUpdateType Type public string PartyName
{ {
get; get;
set; set;
} } // CREATE일 때 사용
} }

View File

@@ -21,6 +21,9 @@ public enum PacketCode : ushort
// 나 채널 접속 (클라 -> 서버) // 나 채널 접속 (클라 -> 서버)
INTO_CHANNEL, INTO_CHANNEL,
// 파티 채널 접속 (클라 -> 서버)
INTO_CHANNEL_PARTY,
// 새로운 유저 채널 접속 (서버 -> 클라) / 유저 채널 나감 (서버 -> 클라) // 새로운 유저 채널 접속 (서버 -> 클라) / 유저 채널 나감 (서버 -> 클라)
UPDATE_CHANNEL_USER, UPDATE_CHANNEL_USER,
@@ -48,11 +51,17 @@ public enum PacketCode : ushort
// 데미지 UI 전달 (서버 -> 클라) // 데미지 UI 전달 (서버 -> 클라)
DAMAGE, DAMAGE,
// 파티 (생성, 삭제) // 파티 생성/삭제, 파티원 추가/제거 (서버 -> 클라)
UPDATE_PARTY, UPDATE_PARTY,
// 파티 유저 업데이트(추가 삭제) // 파티 참가/탈퇴/생성/해산 요청 (클라 -> 서버)
UPDATE_USER_PARTY REQUEST_PARTY,
// 채팅 (클라 -> 서버 & 서버 -> 클라) - GLOBAL / PARTY / WHISPER
CHAT,
// 요청 실패 응답 (서버 -> 클라)
ERROR = 9999
} }
public class PacketHeader public class PacketHeader

View File

@@ -1,3 +1,4 @@
using System.Text.Json;
using ClientTester.DummyService; using ClientTester.DummyService;
using ClientTester.EchoDummyService; using ClientTester.EchoDummyService;
using ClientTester.StressTest; using ClientTester.StressTest;
@@ -8,8 +9,22 @@ class EcoClientTester
{ {
public static string SERVER_IP = "localhost"; public static string SERVER_IP = "localhost";
public static int SERVER_PORT = 9500; public static int SERVER_PORT = 9500;
public static readonly string CONNECTION_KEY = "test"; public static string CONNECTION_KEY = "";
public static int CLIENT_COUNT = 100; public static int CLIENT_COUNT = 50;
private static void LoadConfig()
{
string path = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
if (!File.Exists(path)) return;
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path));
JsonElement root = doc.RootElement;
if (root.TryGetProperty("ServerIp", out JsonElement ip)) SERVER_IP = ip.GetString() ?? SERVER_IP;
if (root.TryGetProperty("ServerPort", out JsonElement port)) SERVER_PORT = port.GetInt32();
if (root.TryGetProperty("ConnectionKey", out JsonElement key)) CONNECTION_KEY = key.GetString() ?? CONNECTION_KEY;
if (root.TryGetProperty("ClientCount", out JsonElement count)) CLIENT_COUNT = count.GetInt32();
}
private async Task StartEchoDummyTest() private async Task StartEchoDummyTest()
{ {
@@ -151,6 +166,9 @@ class EcoClientTester
// 유니코드 문자(═, ║ 등) 콘솔 깨짐 방지 // 유니코드 문자(═, ║ 등) 콘솔 깨짐 방지
Console.OutputEncoding = System.Text.Encoding.UTF8; Console.OutputEncoding = System.Text.Encoding.UTF8;
// appsettings.json 에서 설정 로드
LoadConfig();
// 크래시 덤프 핸들러 (Release: .log + .dmp / Debug: .log) // 크래시 덤프 핸들러 (Release: .log + .dmp / Debug: .log)
CrashDumpHandler.Register(); CrashDumpHandler.Register();
@@ -169,7 +187,7 @@ class EcoClientTester
if (args.Length > 0 && args[0].Equals("stress", StringComparison.OrdinalIgnoreCase)) if (args.Length > 0 && args[0].Equals("stress", StringComparison.OrdinalIgnoreCase))
{ {
// 기본값 // 기본값
CLIENT_COUNT = 50; // CLIENT_COUNT = 50;
int duration = 60; int duration = 60;
int sendInterval = 100; int sendInterval = 100;
int rampInterval = 1000; int rampInterval = 1000;

View File

@@ -18,7 +18,7 @@ public class StressTestClient
private EventBasedNetListener listener; private EventBasedNetListener listener;
private NetDataWriter? writer; private NetDataWriter? writer;
public NetPeer? peer; public NetPeer? peer;
public long clientId; public int clientId;
// 이동 // 이동
private Vector3 position = new Vector3(); private Vector3 position = new Vector3();
@@ -47,7 +47,7 @@ public class StressTestClient
public double AvgRttMs => RttCount > 0 ? TotalRttMs / RttCount : 0; public double AvgRttMs => RttCount > 0 ? TotalRttMs / RttCount : 0;
public bool IsConnected => peer != null; public bool IsConnected => peer != null;
public StressTestClient(long clientId, string ip, int port, string key) public StressTestClient(int clientId, string ip, int port, string key)
{ {
this.clientId = clientId; this.clientId = clientId;
listener = new EventBasedNetListener(); listener = new EventBasedNetListener();
@@ -144,15 +144,15 @@ public class StressTestClient
posX = nextX; posX = nextX;
posZ = nextZ; posZ = nextZ;
distance = hitWall ? 0f : distance - step; distance = hitWall ? 0f : distance - step;
position.X = (int)MathF.Round(posX); position.X = posX;
position.Z = (int)MathF.Round(posZ); position.Z = posZ;
// 전송 // 전송
TransformPlayerPacket pkt = new TransformPlayerPacket TransformPlayerPacket pkt = new TransformPlayerPacket
{ {
PlayerId = (int)clientId, PlayerId = clientId,
RotY = rotY, RotY = rotY,
Position = new Packet.Vector3 { X = position.X, Y = 0, Z = position.Z } Position = new Packet.Position { X = position.X, Y = -0.5f, Z = position.Z }
}; };
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.TRANSFORM_PLAYER, pkt); byte[] data = PacketSerializer.Serialize((ushort)PacketCode.TRANSFORM_PLAYER, pkt);
writer.Put(data); writer.Put(data);

View File

@@ -107,7 +107,7 @@ public class StressTestService
for (int i = 0; i < batch; i++) for (int i = 0; i < batch; i++)
{ {
long id = created + 1; // 1-based (더미 범위) int id = created + 1; // 1-based (더미 범위)
StressTestClient client = new StressTestClient(id, ip, port, key); StressTestClient client = new StressTestClient(id, ip, port, key);
lock (clientsLock) lock (clientsLock)
{ {

View File

@@ -2,7 +2,7 @@ namespace ClientTester;
public class Vector3 public class Vector3
{ {
public int X { get; set; } public float X { get; set; }
public int Y { get; set; } public float Y { get; set; }
public int Z { get; set; } public float Z { get; set; }
} }

View File

@@ -0,0 +1,6 @@
{
"ServerIp": "localhost",
"ServerPort": 9500,
"ConnectionKey": "test",
"ClientCount": 80
}

View File

@@ -0,0 +1,13 @@
namespace MMOserver.Api;
// RestApi.BossRaidAccesssAsync 반환용 도메인 모델
// API 응답(BossRaidAccessResponse)을 직접 노출하지 않고 이걸로 매핑해서 반환
public sealed class BossRaidResult
{
public int RoomId { get; init; }
public string SessionName { get; init; } = string.Empty;
public int BossId { get; init; }
public List<string> Players { get; init; } = new();
public string Status { get; init; } = string.Empty;
public Dictionary<string, string>? Tokens { get; init; }
}

View File

@@ -1,6 +1,7 @@
using System.Net; using System.Net;
using System.Net.Http.Json; using System.Net.Http.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using MMOserver.Config;
using MMOserver.Utils; using MMOserver.Utils;
using Serilog; using Serilog;
@@ -8,22 +9,27 @@ namespace MMOserver.Api;
public class RestApi : Singleton<RestApi> 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 readonly HttpClient httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
private const int MAX_RETRY = 3; private const int MAX_RETRY = 3;
private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(1); private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(1);
public RestApi()
{
httpClient.DefaultRequestHeaders.Add("X-API-Key", AppConfig.RestApi.ApiKey);
}
// 토큰 검증 - 성공 시 username 반환 // 토큰 검증 - 성공 시 username 반환
// 401 → 재시도 없이 즉시 null 반환 (토큰 자체가 무효) // 401 → 재시도 없이 즉시 null 반환 (토큰 자체가 무효)
// 타임아웃/네트워크 오류 → 최대 MAX_RETRY회 재시도 후 null 반환 // 타임아웃/네트워크 오류 → 최대 MAX_RETRY회 재시도 후 null 반환
public async Task<string?> VerifyTokenAsync(string token) public async Task<string?> VerifyTokenAsync(string token)
{ {
string url = AppConfig.RestApi.BaseUrl + AppConfig.RestApi.VerifyToken;
for (int attempt = 1; attempt <= MAX_RETRY; attempt++) for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
{ {
try try
{ {
HttpResponseMessage response = await httpClient.PostAsJsonAsync(VERIFY_URL, new { token }); HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, new { token });
// 401: 토큰 자체가 무효 → 재시도해도 같은 결과, 즉시 반환 // 401: 토큰 자체가 무효 → 재시도해도 같은 결과, 즉시 반환
if (response.StatusCode == HttpStatusCode.Unauthorized) if (response.StatusCode == HttpStatusCode.Unauthorized)
@@ -62,4 +68,110 @@ public class RestApi : Singleton<RestApi>
set; set;
} }
} }
// 레이드 채널 접속 여부 체크
// 성공 시 BossRaidResult 반환, 실패/거절 시 null 반환
public async Task<BossRaidResult?> BossRaidAccessAsync(List<string> userNames, int bossId)
{
string url = AppConfig.RestApi.BaseUrl + "/api/internal/bossraid/entry";
for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
{
try
{
HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, new { usernames = userNames, bossId });
// 401: API 키 인증 실패
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Log.Warning("[RestApi] 보스 레이드 접속 인증 실패 (401)");
return null;
}
// 400: 입장 조건 미충족 / 409: 이미 레이드 중 등
if (response.StatusCode == HttpStatusCode.BadRequest ||
response.StatusCode == HttpStatusCode.Conflict)
{
Log.Warning("[RestApi] 보스 레이드 입장 거절 ({Status}) BossId={BossId}",
(int)response.StatusCode, bossId);
return null;
}
response.EnsureSuccessStatusCode();
BossRaidAccessResponse? raw = await response.Content.ReadFromJsonAsync<BossRaidAccessResponse>();
if (raw == null)
{
return null;
}
// API 응답 → 도메인 모델 매핑
return new BossRaidResult
{
RoomId = raw.RoomId,
SessionName = raw.SessionName ?? string.Empty,
BossId = raw.BossId,
Players = raw.Players,
Status = raw.Status ?? string.Empty,
Tokens = raw.Tokens
};
}
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 BossRaidAccessResponse
{
[JsonPropertyName("roomId")]
public int RoomId
{
get;
set;
}
[JsonPropertyName("sessionName")]
public string? SessionName
{
get;
set;
}
[JsonPropertyName("bossId")]
public int BossId
{
get;
set;
}
[JsonPropertyName("players")]
public List<string> Players
{
get;
set;
} = new();
[JsonPropertyName("status")]
public string? Status
{
get;
set;
}
[JsonPropertyName("tokens")]
public Dictionary<string, string>? Tokens
{
get;
set;
}
}
} }

View File

@@ -0,0 +1,62 @@
using Microsoft.Extensions.Configuration;
namespace MMOserver.Config;
public static class AppConfig
{
public static ServerConfig Server
{
get;
private set;
} = null!;
public static RestApiConfig RestApi
{
get;
private set;
} = null!;
public static void Initialize(IConfiguration config)
{
Server = new ServerConfig(config.GetSection("Server"));
RestApi = new RestApiConfig(config.GetSection("RestApi"));
}
}
public sealed class ServerConfig
{
public int Port
{
get;
}
public ServerConfig(IConfigurationSection section)
{
Port = int.Parse(section["Port"] ?? throw new InvalidOperationException("Server:Port is required in config.json"));
}
}
public sealed class RestApiConfig
{
public string BaseUrl
{
get;
}
public string VerifyToken
{
get;
}
public string ApiKey
{
get;
}
public RestApiConfig(IConfigurationSection section)
{
BaseUrl = section["BaseUrl"] ?? throw new InvalidOperationException("RestApi:BaseUrl is required in config.json");
VerifyToken = section["VerifyToken"] ?? throw new InvalidOperationException("RestApi:BaseUrl is required in config.json");
ApiKey = section["ApiKey"] ?? throw new InvalidOperationException("RestApi:ApiKey is required in config.json");
}
}

View File

@@ -5,7 +5,9 @@ WORKDIR /app
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
ARG BUILD_CONFIGURATION=Release ARG BUILD_CONFIGURATION=Release
WORKDIR /src WORKDIR /src
# ServerLib 의존성 포함해서 restore (캐시 레이어 최적화)
COPY ["MMOserver/MMOserver.csproj", "MMOserver/"] COPY ["MMOserver/MMOserver.csproj", "MMOserver/"]
COPY ["ServerLib/ServerLib.csproj", "ServerLib/"]
RUN dotnet restore "MMOserver/MMOserver.csproj" RUN dotnet restore "MMOserver/MMOserver.csproj"
COPY . . COPY . .
WORKDIR "/src/MMOserver" WORKDIR "/src/MMOserver"

View File

@@ -1,19 +1,51 @@
using LiteNetLib;
using MMOserver.Game.Channel.Maps; using MMOserver.Game.Channel.Maps;
using MMOserver.Game.Channel.Maps.InstanceDungeun;
using MMOserver.Game.Party;
namespace MMOserver.Game.Channel; namespace MMOserver.Game.Channel;
public class Channel public class Channel
{ {
// 로비 // 채널 내 유저 NetPeer (hashKey → NetPeer) — BroadcastToChannel 교차 조회 제거용
private Robby robby = new Robby(); private readonly Dictionary<int, NetPeer> connectPeers = new();
// 채널 내 유저 상태 (hashKey → Player) // 채널 내 유저 상태 (hashKey → Player)
private Dictionary<long, Player> connectUsers = new Dictionary<long, Player>(); private readonly Dictionary<int, Player> connectUsers = new();
// 채널 맵 관리
private readonly Dictionary<int, AMap> maps = new();
// 진행중 채널 맵 관리
private readonly Dictionary<int, AMap> useInstanceMaps = new();
// 동적 레이드 맵 할당용 ID 카운터 (사전 생성 10개 이후부터 시작)
private int nextDynamicRaidMapId = 1011;
// 파티
private readonly PartyManager partyManager = new();
public Channel(int channelId)
{
ChannelId = channelId;
// 일단 하드코딩으로 맵 생성
{
// 로비
maps.Add(1, new Robby(1));
// 인던
int defaultValue = 1000;
for (int i = 1; i <= 10; i++)
{
maps.Add(i + defaultValue, new BossInstance(i + defaultValue));
}
}
}
public int ChannelId public int ChannelId
{ {
get; get;
private set;
} }
public int UserCount public int UserCount
@@ -28,25 +60,60 @@ public class Channel
private set; private set;
} = 100; } = 100;
public Channel(int channelId) public void AddUser(int userId, Player player, NetPeer peer)
{
ChannelId = channelId;
}
public void AddUser(long userId, Player player)
{ {
connectUsers[userId] = player; connectUsers[userId] = player;
connectPeers[userId] = peer;
UserCount++; UserCount++;
// 처음 접속 시 1번 맵(로비)으로 입장
ChangeMap(userId, player, 1);
} }
public void RemoveUser(long userId) public void RemoveUser(int userId)
{ {
connectUsers.Remove(userId); // 현재 맵에서도 제거
UserCount--; if (connectUsers.TryGetValue(userId, out Player? player) &&
maps.TryGetValue(player.CurrentMapId, out AMap? currentMap))
{
currentMap.RemoveUser(userId);
}
if (connectUsers.Remove(userId))
{
UserCount--;
}
connectPeers.Remove(userId);
} }
// 채널 내 모든 유저의 hashKey 반환 // 맵 이동 (현재 맵 제거 → 새 맵 추가 → CurrentMapId 갱신)
public IEnumerable<long> GetConnectUsers() public bool ChangeMap(int userId, Player player, int mapId)
{
if (!maps.TryGetValue(mapId, out AMap? newMap))
{
return false;
}
// 기존 맵에서 제거
if (maps.TryGetValue(player.CurrentMapId, out AMap? oldMap))
{
oldMap.RemoveUser(userId);
}
newMap.AddUser(userId, player);
player.CurrentMapId = mapId;
return true;
}
// 재연결(WiFi→LTE 등) 시 동일 유저의 peer 교체
public void UpdatePeer(int userId, NetPeer peer)
{
connectPeers[userId] = peer;
}
// 채널 내 모든 유저의 hashKey 반환 (채널 입장 시 기존 플레이어 목록 조회용)
public IEnumerable<int> GetConnectUsers()
{ {
return connectUsers.Keys; return connectUsers.Keys;
} }
@@ -57,14 +124,20 @@ public class Channel
return connectUsers.Values; return connectUsers.Values;
} }
// 채널 내 모든 NetPeer 반환 — BroadcastToChannel 전용 (sessions 교차 조회 불필요)
public IEnumerable<NetPeer> GetConnectPeers()
{
return connectPeers.Values;
}
// 특정 유저의 Player 반환 // 특정 유저의 Player 반환
public Player? GetPlayer(long userId) public Player? GetPlayer(int userId)
{ {
connectUsers.TryGetValue(userId, out Player? player); connectUsers.TryGetValue(userId, out Player? player);
return player; return player;
} }
public int HasUser(long userId) public int HasUser(int userId)
{ {
if (connectUsers.ContainsKey(userId)) if (connectUsers.ContainsKey(userId))
{ {
@@ -74,9 +147,61 @@ public class Channel
return -1; return -1;
} }
// 로비 가져옴 // 맵들 가져옴
public Robby GetRobby() public Dictionary<int, AMap> GetMaps()
{ {
return robby; return maps;
} }
// 맵 가져옴
public AMap? GetMap(int mapId)
{
AMap? map = null;
maps.TryGetValue(mapId, out map);
return map;
}
// 사용 가능한 레이드 맵 ID 반환
// 기존 맵(1001~) 중 미사용 탐색 → 없으면 동적 생성 후 반환
public int GetOrCreateAvailableRaidMap()
{
// 기존 맵 중 미사용 탐색
foreach (int mapId in maps.Keys)
{
if (mapId >= 1001 && !useInstanceMaps.ContainsKey(mapId))
{
return mapId;
}
}
// 모두 사용 중 → 동적 생성
int newMapId = nextDynamicRaidMapId++;
BossInstance newMap = new(newMapId);
maps.Add(newMapId, newMap);
return newMapId;
}
// 레이드 맵 사용 시작 (진행중 목록에 등록)
public void AddInstanceMap(int mapId)
{
if (maps.TryGetValue(mapId, out AMap? map))
{
useInstanceMaps[mapId] = map;
}
}
// 레이드 맵 사용 종료 (진행중 목록에서 제거)
public void RemoveInstanceMap(int mapId)
{
useInstanceMaps.Remove(mapId);
}
// 파티매니저 가져옴
public PartyManager GetPartyManager()
{
return partyManager;
}
// TODO : 채널 가져오기
} }

View File

@@ -1,18 +1,19 @@
namespace MMOserver.Game.Channel; using LiteNetLib;
using MMOserver.Utils;
public class ChannelManager namespace MMOserver.Game.Channel;
public class ChannelManager : Singleton<ChannelManager>
{ {
// 일단은 채널은 서버 켤때 고정으로간다 1개
public static ChannelManager Instance
{
get;
} = new ChannelManager();
// 채널 관리 // 채널 관리
private List<Channel> channels = new List<Channel>(); private Dictionary<int, Channel> channels = new Dictionary<int, Channel>();
// 보스 레이드 채널
private readonly int bossChannelStart = 10000;
private readonly int bossChannelSize = 10;
// 채널별 유저 관리 (유저 key, 채널 val) // 채널별 유저 관리 (유저 key, 채널 val)
private Dictionary<long, int> connectUsers = new Dictionary<long, int>(); private Dictionary<int, int> connectUsers = new Dictionary<int, int>();
public ChannelManager() public ChannelManager()
{ {
@@ -21,9 +22,16 @@ public class ChannelManager
public void Initializer(int channelSize = 1) public void Initializer(int channelSize = 1)
{ {
for (int i = 0; i <= channelSize; i++) for (int i = 1; i <= channelSize; i++)
{ {
channels.Add(new Channel(i)); channels.Add(i, new Channel(i));
}
// 보스 채널 생성
for (int i = 1; i <= bossChannelSize; i++)
{
int bossChannel = i + bossChannelStart;
channels.Add(bossChannel, new Channel(bossChannel));
} }
} }
@@ -32,20 +40,20 @@ public class ChannelManager
return channels[channelId]; return channels[channelId];
} }
public List<Channel> GetChannels() public Dictionary<int, Channel> GetChannels()
{ {
return channels; return channels;
} }
public void AddUser(int channelId, long userId, Player player) public void AddUser(int channelId, int userId, Player player, NetPeer peer)
{ {
// 유저 추가 // 유저 추가 (채널 이동 시 기존 매핑 덮어쓰기 허용)
connectUsers.Add(userId, channelId); connectUsers[userId] = channelId;
// 채널에 유저 추가 // 채널에 유저 + peer 추가
channels[channelId].AddUser(userId, player); channels[channelId].AddUser(userId, player, peer);
} }
public bool RemoveUser(long userId) public bool RemoveUser(int userId)
{ {
// 채널에 없는 유저면 스킵 // 채널에 없는 유저면 스킵
if (!connectUsers.TryGetValue(userId, out int channelId)) if (!connectUsers.TryGetValue(userId, out int channelId))
@@ -64,7 +72,7 @@ public class ChannelManager
return false; return false;
} }
public int HasUser(long userId) public int HasUser(int userId)
{ {
int channelId = -1; int channelId = -1;
if (connectUsers.ContainsKey(userId)) if (connectUsers.ContainsKey(userId))
@@ -80,7 +88,7 @@ public class ChannelManager
return channelId; return channelId;
} }
public Dictionary<long, int> GetConnectUsers() public Dictionary<int, int> GetConnectUsers()
{ {
return connectUsers; return connectUsers;
} }

View File

@@ -0,0 +1,24 @@
namespace MMOserver.Game.Channel.Maps;
public abstract class AMap
{
private Dictionary<int, Player> users = new Dictionary<int, Player>();
public abstract EnumMap GetMapType();
public abstract int GetMapId();
public void AddUser(int userId, Player player)
{
users[userId] = player;
}
public void RemoveUser(int userId)
{
users.Remove(userId);
}
public Dictionary<int, Player> GetUsers()
{
return users;
}
}

View File

@@ -0,0 +1,8 @@
namespace MMOserver.Game.Channel.Maps;
public enum EnumMap : int
{
NONE = 0,
ROBBY = 1,
INSTANCE = 10,
}

View File

@@ -0,0 +1,34 @@
using MMOserver.Game.Channel.Maps;
using MMOserver.Game.Engine;
namespace MMOserver.Game.Channel.Maps.InstanceDungeun;
// 인스턴스 보스 맵에 들어갈때 쓰는 것
public class BossInstance : AMap
{
private EnumMap enumMap;
private int mapId;
// 마을 시작 지점 넣어 둔다.
public static Vector3 StartPosition
{
get;
set;
} = new Vector3(0, 0, 0);
public BossInstance(int mapId, EnumMap enumMap = EnumMap.INSTANCE)
{
this.enumMap = enumMap;
this.mapId = mapId;
}
public override EnumMap GetMapType()
{
return enumMap;
}
public override int GetMapId()
{
return mapId;
}
}

View File

@@ -2,8 +2,11 @@
namespace MMOserver.Game.Channel.Maps; namespace MMOserver.Game.Channel.Maps;
public class Robby public class Robby : AMap
{ {
private EnumMap enumMap;
private int mapId;
// 마을 시작 지점 넣어 둔다. // 마을 시작 지점 넣어 둔다.
public static Vector3 StartPosition public static Vector3 StartPosition
{ {
@@ -11,7 +14,19 @@ public class Robby
set; set;
} = new Vector3(0, 0, 0); } = new Vector3(0, 0, 0);
public Robby() public Robby(int mapId, EnumMap enumMap = EnumMap.ROBBY)
{ {
this.enumMap = enumMap;
this.mapId = mapId;
}
public override EnumMap GetMapType()
{
return enumMap;
}
public override int GetMapId()
{
return mapId;
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,52 @@
namespace MMOserver.Game.Party;
public class PartyInfo
{
public static readonly int partyMemberMax = 3;
public int PartyId
{
get;
set;
}
public int LeaderId
{
get;
set;
}
public List<int> PartyMemberIds
{
get;
set;
} = new List<int>();
public string PartyName
{
get;
set;
} = "";
public int GetPartyMemberCount()
{
return PartyMemberIds.Count;
}
public void DeepCopy(PartyInfo other)
{
this.PartyId = other.PartyId;
this.PartyName = other.PartyName;
this.LeaderId = other.LeaderId;
this.PartyMemberIds.Clear();
this.PartyMemberIds.AddRange(other.PartyMemberIds);
}
public void DeepCopySemi(PartyInfo other)
{
this.PartyId = other.PartyId;
this.PartyName = other.PartyName;
this.LeaderId = other.LeaderId;
this.PartyMemberIds = new List<int>();
}
}

View File

@@ -0,0 +1,196 @@
using MMOserver.Utils;
namespace MMOserver.Game.Party;
public class PartyManager
{
private readonly UuidGenerator partyUuidGenerator = new UuidGenerator();
// partyId → PartyInfo
private readonly Dictionary<int, PartyInfo> parties = new();
// playerId → partyId (한 플레이어는 하나의 파티만)
private readonly Dictionary<int, int> playerPartyMap = new();
// 파티 생성
public bool CreateParty(int leaderId, string partyName, out PartyInfo? party, List<int>? memeberIds = null)
{
if (playerPartyMap.ContainsKey(leaderId))
{
party = null;
return false; // 이미 파티에 속해있음
}
int partyId = partyUuidGenerator.Create();
if (memeberIds == null)
{
memeberIds = new List<int>();
}
// 리더 중복 방지: 기존 멤버 목록에 리더가 없을 때만 추가
if (!memeberIds.Contains(leaderId))
{
memeberIds.Add(leaderId);
}
party = new PartyInfo
{
PartyId = partyId,
LeaderId = leaderId,
PartyName = partyName,
PartyMemberIds = memeberIds
};
parties[partyId] = party;
// 모든 멤버를 playerPartyMap에 등록
foreach (int memberId in memeberIds)
{
playerPartyMap[memberId] = partyId;
}
return true;
}
// 파티 참가
public bool JoinParty(int playerId, int partyId, out PartyInfo? party)
{
party = null;
if (playerPartyMap.ContainsKey(playerId))
{
return false; // 이미 파티에 속해있음
}
if (!parties.TryGetValue(partyId, out party))
{
return false; // 파티 없음
}
if (party.GetPartyMemberCount() >= PartyInfo.partyMemberMax)
{
party = null;
return false; // 파티 인원 초과
}
party.PartyMemberIds.Add(playerId);
playerPartyMap[playerId] = partyId;
return true;
}
// 파티 탈퇴
public bool LeaveParty(int playerId, out PartyInfo? party)
{
party = null;
if (!playerPartyMap.TryGetValue(playerId, out int partyId))
{
return false; // 파티에 속해있지 않음
}
if (!parties.TryGetValue(partyId, out party))
{
return false;
}
party.PartyMemberIds.Remove(playerId);
playerPartyMap.Remove(playerId);
// 마지막 멤버가 나가면 파티 해산
if (party.PartyMemberIds.Count == 0)
{
DeletePartyInternal(partyId, party);
// id가 필요하다 그래서 참조해 둔다.
// party = null;
return true;
}
// 리더가 나갔으면 남은 멤버 중 첫 번째를 리더로 승계
if (party.LeaderId == playerId)
{
party.LeaderId = party.PartyMemberIds[0];
}
return true;
}
// 파티 해산 (리더만)
public bool DeleteParty(int leaderId, int partyId, out PartyInfo? party)
{
party = null;
if (!parties.TryGetValue(partyId, out party))
{
return false;
}
if (party.LeaderId != leaderId)
{
party = null;
return false; // 리더만 해산 가능
}
DeletePartyInternal(partyId, party);
return true;
}
// 파티 업데이트
public bool UpdateParty(int leaderId, int partyId, string newPartyName, out PartyInfo? party)
{
party = null;
if (!parties.TryGetValue(partyId, out party))
{
return false;
}
if (party.LeaderId != leaderId)
{
party = null;
return false; // 리더만 업데이트 가능
}
// 파티 이름 변경
party.PartyName = newPartyName;
return true;
}
// 전체 파티 목록 조회
public IEnumerable<PartyInfo> GetAllParties()
{
return parties.Values;
}
// 조회
public PartyInfo? GetParty(int partyId)
{
parties.TryGetValue(partyId, out PartyInfo? party);
return party;
}
public PartyInfo? GetPartyByPlayer(int playerId)
{
if (!playerPartyMap.TryGetValue(playerId, out int partyId))
{
return null;
}
parties.TryGetValue(partyId, out PartyInfo? party);
return party;
}
// 삭제
private void DeletePartyInternal(int partyId, PartyInfo party)
{
// 남아 있는인원도 제거
foreach (int memberId in party.PartyMemberIds)
{
playerPartyMap.Remove(memberId);
}
parties.Remove(partyId);
partyUuidGenerator.Release(partyId);
}
}

View File

@@ -2,7 +2,7 @@ namespace MMOserver.Game;
public class Player public class Player
{ {
public long HashKey public int HashKey
{ {
get; get;
set; set;
@@ -74,4 +74,18 @@ public class Player
get; get;
set; set;
} }
// 현재 위치한 맵 ID
public int CurrentMapId
{
get;
set;
}
// 레이드 입장 전 이전 맵 ID (레이드 종료 후 복귀용, 서버 캐싱)
public int PreviousMapId
{
get;
set;
}
} }

View File

@@ -9,6 +9,11 @@
<LangVersion>13</LangVersion> <LangVersion>13</LangVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<DebugType>portable</DebugType>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="LiteNetLib" Version="2.0.2" /> <PackageReference Include="LiteNetLib" Version="2.0.2" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="10.0.3" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="10.0.3" />

View File

@@ -25,7 +25,7 @@ public class EchoPacket
// ============================================================ // ============================================================
[ProtoContract] [ProtoContract]
public class Vector3 public class Position
{ {
[ProtoMember(1)] [ProtoMember(1)]
public float X public float X
@@ -102,7 +102,7 @@ public class PlayerInfo
} }
[ProtoMember(8)] [ProtoMember(8)]
public Vector3 Position public Position Position
{ {
get; get;
set; set;
@@ -114,6 +114,41 @@ public class PlayerInfo
get; get;
set; set;
} }
[ProtoMember(10)]
public int Experience
{
get;
set;
}
[ProtoMember(11)]
public int NextExp
{
get;
set;
}
[ProtoMember(12)]
public float AttackPower
{
get;
set;
}
[ProtoMember(13)]
public float AttackRange
{
get;
set;
}
[ProtoMember(14)]
public float SprintMultiplier
{
get;
set;
}
} }
// ============================================================ // ============================================================
@@ -125,7 +160,7 @@ public class PlayerInfo
public class DummyAccTokenPacket public class DummyAccTokenPacket
{ {
[ProtoMember(1)] [ProtoMember(1)]
public long Token public int Token
{ {
get; get;
set; set;
@@ -163,7 +198,7 @@ public class LoadGamePacket
} }
[ProtoMember(3)] [ProtoMember(3)]
public int MaplId public int MapId
{ {
get; get;
set; set;
@@ -185,7 +220,7 @@ public class ChannelInfo
} }
[ProtoMember(2)] [ProtoMember(2)]
public int ChannelUserConut public int ChannelUserCount
{ {
get; get;
set; set;
@@ -210,6 +245,39 @@ public class LoadChannelPacket
} = new List<ChannelInfo>(); } = new List<ChannelInfo>();
} }
// 채널 내 파티 정보 (INTO_CHANNEL 응답에 포함)
[ProtoContract]
public class PartyInfoData
{
[ProtoMember(1)]
public int PartyId
{
get;
set;
}
[ProtoMember(2)]
public int LeaderId
{
get;
set;
}
[ProtoMember(3)]
public List<int> MemberPlayerIds
{
get;
set;
} = new List<int>();
[ProtoMember(4)]
public string PartyName
{
get;
set;
}
}
// INTO_CHANNEL 클라->서버: 입장할 채널 ID / 서버->클라: 채널 내 나 이외 플레이어 목록 // INTO_CHANNEL 클라->서버: 입장할 채널 ID / 서버->클라: 채널 내 나 이외 플레이어 목록
[ProtoContract] [ProtoContract]
public class IntoChannelPacket public class IntoChannelPacket
@@ -227,6 +295,47 @@ public class IntoChannelPacket
get; get;
set; set;
} = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록 } = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록
[ProtoMember(3)]
public List<PartyInfoData> Parties
{
get;
set;
} = new List<PartyInfoData>(); // 서버->클라: 채널 내 파티 목록
}
// 파티원 모두 채널이동
// 클라->서버: 입장할 채널 ID
[ProtoContract]
public class IntoChannelPartyPacket
{
[ProtoMember(1)]
public int ChannelId
{
get;
set;
} // 클라->서버: 입장할 채널 ID
[ProtoMember(2)]
public List<PlayerInfo> Players
{
get;
set;
} = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록
[ProtoMember(3)]
public List<PartyInfoData> Parties
{
get;
set;
} = new List<PartyInfoData>(); // 서버->클라: 채널 내 파티 목록
[ProtoMember(4)]
public int PartyId
{
get;
set;
}
} }
// UPDATE_CHANNEL_USER 유저 접속/나감 // UPDATE_CHANNEL_USER 유저 접속/나감
@@ -287,7 +396,7 @@ public class TransformPlayerPacket
} }
[ProtoMember(2)] [ProtoMember(2)]
public Vector3 Position public Position Position
{ {
get; get;
set; set;
@@ -399,7 +508,7 @@ public class TransformNpcPacket
} }
[ProtoMember(2)] [ProtoMember(2)]
public Vector3 Position public Position Position
{ {
get; get;
set; set;
@@ -516,6 +625,32 @@ public class DamagePacket
} }
} }
// ============================================================
// 에러
// ============================================================
public enum ErrorCode : int
{
// 파티 (10021~)
PARTY_ALREADY_IN_PARTY = 10021,
PARTY_JOIN_FAILED = 10022,
PARTY_NOT_IN_PARTY = 10023,
PARTY_DELETE_FAILED = 10024,
PARTY_UPDATE_FAILED = 10025,
}
// ERROR (서버 -> 클라)
[ProtoContract]
public class ErrorPacket
{
[ProtoMember(1)]
public ErrorCode Code
{
get;
set;
}
}
// ============================================================ // ============================================================
// 파티 // 파티
// ============================================================ // ============================================================
@@ -523,16 +658,193 @@ public class DamagePacket
public enum PartyUpdateType public enum PartyUpdateType
{ {
CREATE, CREATE,
DELETE DELETE,
}
public enum UserPartyUpdateType
{
JOIN, JOIN,
LEAVE LEAVE,
UPDATE
} }
// UPDATE_PARTY // REQUEST_PARTY (클라 -> 서버) - CREATE: PartyName 사용 / JOIN·LEAVE·DELETE: PartyId 사용
[ProtoContract]
public class RequestPartyPacket
{
[ProtoMember(1)]
public PartyUpdateType Type
{
get;
set;
}
[ProtoMember(2)]
public int PartyId
{
get;
set;
} // JOIN, LEAVE, DELETE 시 사용
[ProtoMember(3)]
public string PartyName
{
get;
set;
} // CREATE 시 사용
}
// ============================================================
// 채팅
// ============================================================
public enum ChatType
{
GLOBAL, // 전체 채널
PARTY, // 파티원
WHISPER // 귓말
}
// CHAT (클라 -> 서버 & 서버 -> 클라)
// 클라->서버: Type, TargetId(WHISPER 시), Message
// 서버->클라: Type, SenderId, SenderNickname, TargetId(WHISPER 시), Message
[ProtoContract]
public class ChatPacket
{
[ProtoMember(1)]
public ChatType Type
{
get;
set;
}
[ProtoMember(2)]
public int SenderId
{
get;
set;
} // 서버에서 채워줌
[ProtoMember(3)]
public string SenderNickname
{
get;
set;
} // 서버에서 채워줌
[ProtoMember(4)]
public int TargetId
{
get;
set;
} // WHISPER일 때 대상 PlayerId
[ProtoMember(5)]
public string Message
{
get;
set;
}
}
// ============================================================
// 맵 이동
// ============================================================
// CHANGE_MAP (클라 -> 서버 & 서버 -> 클라)
[ProtoContract]
public class ChangeMapPacket
{
[ProtoMember(1)]
public int MapId
{
get;
set;
}
// 새 맵의 기존 플레이어 목록 (이동한 본인에게 전달)
[ProtoMember(2)]
public List<PlayerInfo> Players
{
get;
set;
} = new List<PlayerInfo>();
// 입장(true) / 퇴장(false) - 기존 맵 플레이어들에게 전달
[ProtoMember(3)]
public bool IsAdd
{
get;
set;
}
// 이동한 플레이어 정보 - 기존 맵 플레이어들에게 전달
[ProtoMember(4)]
public PlayerInfo Player
{
get;
set;
}
}
// INTO_BOSS_RAID
// 클라->서버: RaidId
// 서버->클라: RaidId + IsSuccess (파티장에게 결과 전달)
// 성공 시 파티원 전체에게 CHANGE_MAP 추가 전송
[ProtoContract]
public class IntoBossRaidPacket
{
// 입장할 보스 레이드 맵 Id
[ProtoMember(1)]
public int RaidId
{
get;
set;
}
// 입장 성공 여부 (서버 -> 클라)
[ProtoMember(2)]
public bool IsSuccess
{
get;
set;
}
[ProtoMember(3)]
public string Token
{
get;
set;
}
[ProtoMember(4)]
public string Session
{
get;
set;
}
}
// PARTY_CHANGE_MAP (클라 -> 서버 전용)
[ProtoContract]
public class PartyChangeMapPacket
{
[ProtoMember(1)]
public int MapId
{
get;
set;
}
[ProtoMember(2)]
public int PartyId
{
get;
set;
}
}
// ============================================================
// 파티
// ============================================================
// UPDATE_PARTY (서버 -> 클라) - 파티 생성/삭제: LeaderId 사용 / 파티원 추가/제거: PlayerId 사용
[ProtoContract] [ProtoContract]
public class UpdatePartyPacket public class UpdatePartyPacket
{ {
@@ -556,30 +868,18 @@ public class UpdatePartyPacket
get; get;
set; set;
} }
}
// UPDATE_USER_PARTY [ProtoMember(4)]
[ProtoContract]
public class UpdateUserPartyPacket
{
[ProtoMember(1)]
public int PartyId
{
get;
set;
}
[ProtoMember(2)]
public int PlayerId public int PlayerId
{ {
get; get;
set; set;
} }
[ProtoMember(3)] [ProtoMember(5)]
public UserPartyUpdateType Type public string PartyName
{ {
get; get;
set; set;
} } // CREATE일 때 사용
} }

View File

@@ -2,57 +2,75 @@ namespace MMOserver.Packet;
public enum PacketCode : ushort public enum PacketCode : ushort
{ {
// 초기 클라이언트 시작시 jwt토큰 받아옴
ACC_TOKEN = 1,
// 내 정보 로드 (서버 -> 클라)
LOAD_GAME = 2,
// 모든 채널 로드 - jwt토큰 검증후 게임에 들어갈지 말지 (내 데이터도 전송)
// (서버 -> 클라)
LOAD_CHANNEL = 3,
// 나 채널 접속 (클라 -> 서버)
INTO_CHANNEL = 4,
// 파티 채널 접속 (클라 -> 서버)
INTO_CHANNEL_PARTY = 5,
// 새로운 유저 채널 접속 (서버 -> 클라) / 유저 채널 나감 (서버 -> 클라)
UPDATE_CHANNEL_USER = 6,
// 채널 나가기 (클라 -> 서버)
EXIT_CHANNEL = 7,
// 맵 이동
CHANGE_MAP = 8,
// 단체로 맵 이동
PARTY_CHANGE_MAP = 9,
// 파티장이 보스 레이드(인스턴스 던전) 입장 신청 (클라 -> 서버)
INTO_BOSS_RAID = 10,
// 플레이어 위치, 방향 (서버 -> 클라 \ 클라 -> 서버)
TRANSFORM_PLAYER = 11,
// 플레이어 행동 업데이트 (서버 -> 클라 \ 클라 -> 서버)
ACTION_PLAYER = 12,
// 플레이어 스테이트 업데이트 (서버 -> 클라 \ 클라 -> 서버)
STATE_PLAYER = 13,
// NPC 위치, 방향 (서버 -> 클라)
TRANSFORM_NPC = 14,
// NPC 행동 업데이트 (서버 -> 클라)
ACTION_NPC = 15,
// NPC 스테이트 업데이트 (서버 -> 클라)
STATE_NPC = 16,
// 데미지 UI 전달 (서버 -> 클라)
DAMAGE = 17,
// 파티 생성/삭제, 파티원 추가/제거 (서버 -> 클라)
UPDATE_PARTY = 18,
// 파티 참가/탈퇴/생성/해산 요청 (클라 -> 서버)
REQUEST_PARTY = 19,
// 채팅 (클라 -> 서버 & 서버 -> 클라) - GLOBAL / PARTY / WHISPER
CHAT = 20,
// ECHO // ECHO
ECHO = 1000, ECHO = 1000,
// DUMMY 클라는 이걸로 jwt토큰 안받음 // DUMMY 클라는 이걸로 jwt토큰 안받음
DUMMY_ACC_TOKEN = 1001, DUMMY_ACC_TOKEN = 1001,
// 초기 클라이언트 시작시 jwt토큰 받아옴 // 요청 실패 응답 (서버 -> 클라)
ACC_TOKEN = 1, ERROR = 9999
// 내 정보 로드 (서버 -> 클라)
LOAD_GAME,
// 모든 채널 로드 - jwt토큰 검증후 게임에 들어갈지 말지 (내 데이터도 전송)
// (서버 -> 클라)
LOAD_CHANNEL,
// 나 채널 접속 (클라 -> 서버)
INTO_CHANNEL,
// 새로운 유저 채널 접속 (서버 -> 클라) / 유저 채널 나감 (서버 -> 클라)
UPDATE_CHANNEL_USER,
// 채널 나가기 (클라 -> 서버)
EXIT_CHANNEL,
// 플레이어 위치, 방향 (서버 -> 클라 \ 클라 -> 서버)
TRANSFORM_PLAYER,
// 플레이어 행동 업데이트 (서버 -> 클라 \ 클라 -> 서버)
ACTION_PLAYER,
// 플레이어 스테이트 업데이트 (서버 -> 클라 \ 클라 -> 서버)
STATE_PLAYER,
// NPC 위치, 방향 (서버 -> 클라)
TRANSFORM_NPC,
// NPC 행동 업데이트 (서버 -> 클라)
ACTION_NPC,
// NPC 스테이트 업데이트 (서버 -> 클라)
STATE_NPC,
// 데미지 UI 전달 (서버 -> 클라)
DAMAGE,
// 파티 (생성, 삭제)
UPDATE_PARTY,
// 파티 유저 업데이트(추가 삭제)
UPDATE_USER_PARTY
} }
public class PacketHeader public class PacketHeader

View File

@@ -1,4 +1,5 @@
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using MMOserver.Config;
using MMOserver.Game; using MMOserver.Game;
using MMOserver.RDB; using MMOserver.RDB;
using Serilog; using Serilog;
@@ -21,6 +22,8 @@ class Program
.AddEnvironmentVariables() // 도커 배포용 .AddEnvironmentVariables() // 도커 배포용
.Build(); .Build();
AppConfig.Initialize(config);
// DB 연결 // DB 연결
// DbConnectionFactory dbFactory = new DbConnectionFactory(config); // DbConnectionFactory dbFactory = new DbConnectionFactory(config);
@@ -34,7 +37,7 @@ class Program
Log.Information("Write Log Started"); Log.Information("Write Log Started");
int port = 9500; int port = AppConfig.Server.Port;
string connectionString = "test"; string connectionString = "test";
GameServer gameServer = new GameServer(port, connectionString); GameServer gameServer = new GameServer(port, connectionString);

View File

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

View File

@@ -1,4 +1,12 @@
{ {
"Server": {
"Port": 9500
},
"RestApi": {
"BaseUrl": "https://a301.api.tolelom.xyz",
"VerifyToken": "/api/internal/auth/verify",
"ApiKey": "017f15b28143fc67d2e5bed283c37d2da858b9f294990a5334238e055e3f5425"
},
"Database": { "Database": {
"Host": "localhost", "Host": "localhost",
"Port": "0000", "Port": "0000",

View File

@@ -277,9 +277,106 @@ Docker Compose (compose.yaml)
--- ---
## 4. 문제점 - 해결 ## 4. 버그 및 잠재적 이슈
### 4.1 해결된 문제 > 코드 정적 분석을 통해 발견된 버그 및 잠재적 문제점 목록입니다.
### 4.1 버그 목록
#### [B1] Engine Vector3 타입 불일치 (HIGH)
- **파일**: `MMOserver/Game/Engine/Vector3.cs` vs `MMOserver/Packet/PacketBody.cs`
- **문제**: 두 Vector3 클래스가 다른 타입으로 정의됨
- `Engine/Vector3.cs`: 좌표가 `int` 타입
- `Packet/PacketBody.cs` (PacketVector3): 좌표가 `float` 타입
- **영향**: 실제 코드에서는 Packet Vector3만 사용되고 Engine Vector3는 사용되지 않음. 향후 Engine Vector3를 사용하는 코드가 생기면 타입 캐스팅 오류 발생
- **권장 조치**: Engine Vector3 제거 또는 float 기반으로 통일
#### [B2] ChannelManager.AddUser() 스레드 안전성 문제 (MEDIUM)
- **파일**: `MMOserver/Game/Channel/ChannelManager.cs`
- **문제**: 비동기 인증 흐름(JWT 검증 → AddUser) 후 두 요청이 동시에 같은 userId로 `connectUsers.Add()`를 호출할 경우 `ArgumentException` 발생 가능
```csharp
public void AddUser(int channelId, long userId, Player player)
{
connectUsers.Add(userId, channelId); // 중복 키 시 예외 발생
channels[channelId].AddUser(userId, player);
}
```
- **영향**: 동시 재접속 시나리오에서 서버 크래시 가능성
- **권장 조치**: `TryAdd()` 사용 또는 `lock` 추가
#### [B3] PlayerId 정수 오버플로우로 인한 중복 ID (LOW)
- **파일**: `MMOserver/Game/GameServer.cs`
- **문제**: `PlayerId = (int)(hashKey & 0x7FFFFFFF)` 계산으로 서로 다른 hashKey가 동일한 PlayerId를 생성할 수 있음
- 예: `hashKey=1` → PlayerId=1, `hashKey=2147483649` → PlayerId=1 (동일)
- **영향**: ID 기반 플레이어 조회 오작동
- **권장 조치**: PlayerId로 hashKey 원본(long) 사용
#### [B4] TokenHash 딕셔너리 무한 증가 (MEDIUM)
- **파일**: `ServerLib/Service/ServerBase.cs`
- **문제**: 토큰 만료 또는 로그아웃 시 `tokenHash` 딕셔너리에서 항목이 제거되지 않음. 장기 운영 시 모든 누적 토큰이 메모리에 남음
- **영향**: 장기 운영 서버에서 메모리 누수 (ex. 100만 로그인 이후 100만 항목 유지)
- **권장 조치**: 로그아웃/연결 해제 시 `tokenHash.Remove()` 호출, 또는 TTL 기반 만료 캐시 도입
#### [B5] 패킷 역직렬화 크기 검증 없음 (MEDIUM)
- **파일**: `ServerLib/Service/ServerBase.cs`
- **문제**: 패킷 페이로드가 `null`인지는 확인하지만, 역직렬화된 객체의 필드 크기는 검증하지 않음
- **영향**: 악의적으로 구성된 패킷(예: PlayerInfo 리스트 내 수만 개의 항목)이 메모리 과소비 유발 가능
- **권장 조치**: 역직렬화 전 페이로드 바이트 크기 상한 검증 추가
#### [B6] Echo 패킷에 레이트 리미팅 미적용 (MEDIUM)
- **파일**: `MMOserver/Game/GameServer.cs`
- **문제**: Echo 패킷 처리 경로가 세션 인증 및 레이트 리미팅 검사를 우회함
- **영향**: 인증 전 클라이언트가 Echo 패킷을 무제한으로 전송하여 서버 자원 소모 가능 (DoS)
- **권장 조치**: Echo 처리 경로에도 레이트 리미팅 적용
---
## 5. 최적화 미비점
### 5.1 성능 병목
#### ~~[O1] BroadcastToChannel 내 반복적 딕셔너리 조회~~ ✅ 해결됨
- **해결**: `Channel``Dictionary<long, NetPeer> connectPeers` 추가, `BroadcastToChannel``GetConnectPeers()`를 직접 순회하도록 변경
- **변경 파일**: `Channel.cs`, `ChannelManager.cs`, `GameServer.cs`
- **효과**: 100명 채널 브로드캐스트 시 `sessions` 딕셔너리 교차 조회 100회 → 0회 제거
- **추가 처리**: 재연결(WiFi→LTE) 시 `Channel.UpdatePeer()`로 peer 참조 갱신
#### [O2] Transform 패킷 객체 풀링 미구현
- **파일**: `ServerLib/Packet/PacketSerializer.cs`
- **문제**: 매 패킷마다 새 객체 생성 및 Protobuf 리플렉션 수행. Transform 패킷은 초당 수백~수천 회 발생하는 고빈도 패킷
- **권장 조치**: `ObjectPool<T>` 도입으로 GC 압박 감소
#### [O3] Dictionary 열거 시 Enumerator 힙 할당
- **현황**: 모든 열거 메서드(`GetConnectUsers`, `GetPlayers`, `GetConnectPeers`)를 `IEnumerable<T>`로 통일
- **판단 근거**: 박싱 비용(수 나노초)이 실질적으로 무시 가능한 수준이며, `IEnumerable<T>`가 가독성과 인터페이스 일관성 면에서 유리
- **미적용 사유**: 가독성 > 마이크로 최적화 우선
#### [O4] 레이트 리미터 고정 윈도우 방식
- **파일**: `ServerLib/Service/Session.cs`
- **문제**: 현재 고정 윈도우(Fixed Window) 방식 사용. 윈도우 경계에서 최대 2배 패킷 폭주 허용 가능
- 예: 윈도우 끝 120개 + 새 윈도우 시작 120개 = 240개/초 순간 처리
- **권장 조치**: 슬라이딩 윈도우 또는 토큰 버킷 알고리즘으로 교체
#### [O5] 로깅 문자열 할당
- **현황**: 모든 패킷 처리마다 Serilog 메시지 템플릿 평가 발생
- **권장 조치**: `if (Log.IsEnabled(LogEventLevel.Debug))` 가드 추가로 Debug 레벨 불필요한 평가 방지
---
## 6. 문제점 - 해결
### 6.1 해결된 문제
#### [P1] 이동 패킷 재전송 문제 #### [P1] 이동 패킷 재전송 문제
- **문제**: 이동(Transform) 패킷이 `ReliableOrdered`로 전송되어 패킷 손실 시 재전송 발생 → 위치 동기화 지연, Head-of-Line 블로킹 - **문제**: 이동(Transform) 패킷이 `ReliableOrdered`로 전송되어 패킷 손실 시 재전송 발생 → 위치 동기화 지연, Head-of-Line 블로킹
@@ -326,7 +423,7 @@ Docker Compose (compose.yaml)
- `Program.cs`: CLI 인자 지원 (`stress -c 100 -d 60 --ip ...`) + 대화형 모드 3번 메뉴 - `Program.cs`: CLI 인자 지원 (`stress -c 100 -d 60 --ip ...`) + 대화형 모드 3번 메뉴
- **효과**: N명 동시접속 시나리오 자동 검증, 성능 병목 지점 파악 - **효과**: N명 동시접속 시나리오 자동 검증, 성능 병목 지점 파악
### 4.2 현재 남아 있는 문제 ### 6.2 현재 남아 있는 문제
#### [I1] 서버 사이드 위치 검증 미구현 #### [I1] 서버 사이드 위치 검증 미구현
- **현상**: 클라이언트가 전송하는 위치를 서버에서 검증하지 않음 - **현상**: 클라이언트가 전송하는 위치를 서버에서 검증하지 않음
@@ -334,20 +431,20 @@ Docker Compose (compose.yaml)
- **권장**: `MapBounds` 로직을 서버 사이드에 적용, 비정상 이동 감지 시 보정 - **권장**: `MapBounds` 로직을 서버 사이드에 적용, 비정상 이동 감지 시 보정
#### [I2] 플레이어 데이터 DB 연동 미완성 #### [I2] 플레이어 데이터 DB 연동 미완성
- **현상**: 플레이어 데이터가 하드코딩된 기본값 사용 (TODO 주석 존재) - **현상**: 플레이어 데이터가 하드코딩된 기본값 사용 (GameServer.cs 내 TODO 주석 존재)
- **영향**: 캐릭터 정보 저장/불러오기 불가 - **영향**: 캐릭터 정보 저장/불러오기 불가, 레벨·닉네임·HP/MP 등 지속성 없음
- **권장**: Player 모델 DB 테이블 생성, 로그인 시 DB 조회 - **권장**: Player 모델 DB 테이블 생성, 로그인 시 DB 조회
#### [I3] NPC / 파티 시스템 미구현 #### [I3] NPC / 파티 시스템 미구현
- **현상**: 패킷 코드(TRANSFORM_NPC, ACTION_NPC, UPDATE_PARTY 등)는 정의되어 있으나 처리 로직 없음 - **현상**: 패킷 코드(`TRANSFORM_NPC`, `ACTION_NPC`, `UPDATE_PARTY` 등)는 정의되어 있으나 핸들러 없음
- **영향**: 게임 콘텐츠 부족 - **영향**: 수신 시 경고 로그만 출력되고 무시됨
- **권장**: NPC AI 시스템, 파티 매칭 로직 순차 구현 - **권장**: NPC AI 시스템, 파티 매칭 로직 순차 구현
--- ---
## 5. 정리 ## 7. 정리
### 5.1 아키텍처 요약 ### 7.1 아키텍처 요약
``` ```
┌──────────────────────────────────────────────────────┐ ┌──────────────────────────────────────────────────────┐
@@ -376,7 +473,7 @@ Docker Compose (compose.yaml)
└──────────────────────────────┘ └──────────────────────────────┘
``` ```
### 5.2 기술적 강점 ### 7.2 기술적 강점
| 항목 | 내용 | | 항목 | 내용 |
|------|------| |------|------|
@@ -389,19 +486,21 @@ Docker Compose (compose.yaml)
| 계층화된 DB 구조 | Handler-Service-Repository 패턴 | | 계층화된 DB 구조 | Handler-Service-Repository 패턴 |
| Docker 배포 | 컨테이너화된 일관된 배포 환경 | | Docker 배포 | 컨테이너화된 일관된 배포 환경 |
### 5.3 향후 작업 (Roadmap) ### 7.3 향후 작업 (Roadmap)
| 우선순위 | 작업 | 설명 | | 우선순위 | 작업 | 설명 |
|---------|------|------| |---------|------|------|
| **높음** | 플레이어 DB 연동 | 캐릭터 정보 저장/불러오기 완성 | | **높음** | 플레이어 DB 연동 | 캐릭터 정보 저장/불러오기 완성 (I2) |
| **높음** | 서버 사이드 위치 검증 | 치트 방어를 위한 이동 유효성 검사 | | **높음** | 버그 수정 | B2 스레드 안전성, B4 메모리 누수, B6 Echo 레이트 리미팅 |
| **중간** | NPC 시스템 | AI 기반 NPC 이동/전투 로직 | | **높음** | 서버 사이드 위치 검증 | 치트 방어를 위한 이동 유효성 검사 (I1) |
| **낮음** | 파티 시스템 | 파티 생성/참여/매칭 | | **중간** | NPC 시스템 | AI 기반 NPC 이동/전투 로직 (I3) |
| **중간** | 성능 최적화 | ~~O1 브로드캐스트 최적화 (완료)~~, O2 객체 풀링, O4 레이트 리미터 개선 |
| **낮음** | 파티 시스템 | 파티 생성/참여/매칭 (I3) |
| **낮음** | 모니터링 대시보드 | 서버 상태/접속자 수 실시간 모니터링 | | **낮음** | 모니터링 대시보드 | 서버 상태/접속자 수 실시간 모니터링 |
> **완료된 항목**: 토큰 캐시 정리 (기 구현 확인), 패킷 레이트 리미팅 (적용 완료), 부하 테스트 도구 (구현 완료) > **완료된 항목**: 패킷 레이트 리미팅 (적용 완료), 부하 테스트 도구 (구현 완료), 크래시 덤프 (적용 완료), O1 브로드캐스트 최적화 (적용 완료)
### 5.4 부하 테스트 도구 (StressTest) ### 7.4 부하 테스트 도구 (StressTest)
`ClientTester/EchoClientTester/StressTest/` 에 구현됨. `ClientTester/EchoClientTester/StressTest/` 에 구현됨.
@@ -473,10 +572,14 @@ dotnet run -- stress \
╚═══════════════════════════════════════════════╝ ╚═══════════════════════════════════════════════╝
``` ```
### 5.5 최근 개발 이력 ### 7.5 최근 개발 이력
| 커밋 | 내용 | | 커밋 | 내용 |
|------|------| |------|------|
| `85c3276` | 세션 끊길 때 같은 채널에 퇴장 메시지 전송 |
| `c27e846` | 채널 버그 수정 |
| `d4c5a70` | 채널 버그 수정 |
| `ea3f64a` | 스트레스 테스트 기능 추가 / 패킷 처리량 제한 / 프로젝트 상황 README 추가 |
| `2be1302` | 크래시 덤프 기능 추가 (Release: 힙 덤프) | | `2be1302` | 크래시 덤프 기능 추가 (Release: 힙 덤프) |
| `42f0ef1` | 이동 패킷 Unreliable 전송으로 변경 | | `42f0ef1` | 이동 패킷 Unreliable 전송으로 변경 |
| `bfa3394` | 토큰 → HashKey 생성 로직 구조 변경 | | `bfa3394` | 토큰 → HashKey 생성 로직 구조 변경 |
@@ -485,5 +588,9 @@ dotnet run -- stress \
--- ---
> **작성일**: 2026-03-05 > **작성일**: 2026-03-06
> **프로젝트 상태**: 핵심 네트워크 인프라 완성, 게임 콘텐츠 확장 단계 > **프로젝트 상태**: 핵심 네트워크 인프라 완성, 게임 콘텐츠 확장 단계
>
> **구현 완료**: 네트워크 코어, 세션 관리, 채널 시스템, 인증, 레이트 리미팅, 크래시 덤프, 부하 테스트 도구
> **미구현**: 플레이어 DB 연동, NPC/파티 시스템, 서버 사이드 위치 검증, 전투/아이템 시스템
> **알려진 버그**: B1 Vector3 타입 불일치, B2 ChannelManager 스레드 안전성, B4 TokenHash 메모리 누수, B6 Echo DoS 취약점

View File

@@ -15,7 +15,7 @@ namespace ServerLib.Service;
/// ///
/// 흐름: /// 흐름:
/// OnPeerConnected → 대기 목록 등록 /// OnPeerConnected → 대기 목록 등록
/// OnNetworkReceive → Auth 패킷(type=1)이면 HashKey(8byte long) 읽어 인증 /// OnNetworkReceive → Auth 패킷(type=1)이면 HashKey(4byte int) 읽어 인증
/// → 이미 같은 HashKey 세션 있으면 이전 피어 끊고 재연결 (WiFi→LTE) /// → 이미 같은 HashKey 세션 있으면 이전 피어 끊고 재연결 (WiFi→LTE)
/// → 그 외 패킷은 HandlePacket() 으로 전달 /// → 그 외 패킷은 HandlePacket() 으로 전달
/// OnPeerDisconnected → 세션/대기 목록에서 제거 /// OnPeerDisconnected → 세션/대기 목록에서 제거
@@ -34,14 +34,17 @@ public abstract class ServerBase : INetEventListener
// 인증된 세션 (hashKey → NetPeer) 재연결 조회용 // 인증된 세션 (hashKey → NetPeer) 재연결 조회용
// peer → hashKey 역방향은 peer.Tag as Session 으로 대체 // peer → hashKey 역방향은 peer.Tag as Session 으로 대체
protected readonly Dictionary<long, NetPeer> sessions = new(); protected readonly Dictionary<int, NetPeer> sessions = new();
// Token / HashKey 관리 // Token / HashKey 관리
protected readonly Dictionary<string, long> tokenHash = new(); protected readonly Dictionary<string, int> tokenHash = new();
// 재사용 NetDataWriter (단일 스레드 폴링이므로 안전) // 재사용 NetDataWriter (단일 스레드 폴링이므로 안전)
private readonly NetDataWriter cachedWriter = new(); private readonly NetDataWriter cachedWriter = new();
// async 메서드(HandleAuth 등)의 await 이후 공유 자원 접근 보호용
protected readonly object sessionLock = new();
// 핑 로그 출력 여부 // 핑 로그 출력 여부
public bool PingLogRtt public bool PingLogRtt
{ {
@@ -118,26 +121,29 @@ public abstract class ServerBase : INetEventListener
// 클라이언트가 연결 해제됐을 때 (타임아웃, 명시적 끊기 등) // 클라이언트가 연결 해제됐을 때 (타임아웃, 명시적 끊기 등)
public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
{ {
pendingPeers.Remove(peer.Id); lock (sessionLock)
if (peer.Tag is Session session)
{ {
// 현재 인증된 피어가 이 peer일 때만 세션 제거 pendingPeers.Remove(peer.Id);
// (재연결로 이미 교체된 경우엔 건드리지 않음)
if (sessions.TryGetValue(session.HashKey, out NetPeer? current) && current.Id == peer.Id) if (peer.Tag is Session session)
{ {
// 더미 클라 아니면 token관리 // 현재 인증된 피어가 이 peer일 때만 세션 제거
if (!string.IsNullOrEmpty(session.Token)) // (재연결로 이미 교체된 경우엔 건드리지 않음)
if (sessions.TryGetValue(session.HashKey, out NetPeer? current) && current.Id == peer.Id)
{ {
tokenHash.Remove(session.Token); // 더미 클라 아니면 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);
} }
sessions.Remove(session.HashKey); peer.Tag = null;
Log.Information("[Server] 세션 해제 HashKey={Key} Reason={Reason}", session.HashKey, disconnectInfo.Reason);
OnSessionDisconnected(peer, session.HashKey, disconnectInfo);
} }
peer.Tag = null;
} }
} }
@@ -167,7 +173,11 @@ public abstract class ServerBase : INetEventListener
// Auth 패킷은 베이스에서 처리 (raw 8-byte long, protobuf 불필요) // Auth 패킷은 베이스에서 처리 (raw 8-byte long, protobuf 불필요)
if (type == (ushort)PacketType.ACC_TOKEN) if (type == (ushort)PacketType.ACC_TOKEN)
{ {
HandleAuth(peer, payload); _ = HandleAuth(peer, payload).ContinueWith(t =>
{
if (t.IsFaulted)
Log.Error(t.Exception, "[Server] HandleAuth 예외 PeerId={Id}", peer.Id);
}, TaskContinuationOptions.OnlyOnFaulted);
return; return;
} }
else if (type == (ushort)PacketType.DUMMY_ACC_TOKEN) else if (type == (ushort)PacketType.DUMMY_ACC_TOKEN)
@@ -240,7 +250,7 @@ public abstract class ServerBase : INetEventListener
// ─── Auth 처리 ──────────────────────────────────────────────── // ─── Auth 처리 ────────────────────────────────────────────────
protected abstract void HandleAuth(NetPeer peer, byte[] payload); protected abstract Task HandleAuth(NetPeer peer, byte[] payload);
// ─── 전송 헬퍼 ─────────────────────────────────────────────────────── // ─── 전송 헬퍼 ───────────────────────────────────────────────────────
@@ -271,11 +281,11 @@ public abstract class ServerBase : INetEventListener
// ─── 서브클래스 구현 ───────────────────────────────────────────────── // ─── 서브클래스 구현 ─────────────────────────────────────────────────
// 인증(Auth) 완료 후 호출 // 인증(Auth) 완료 후 호출
protected abstract void OnSessionConnected(NetPeer peer, long hashKey); protected abstract void OnSessionConnected(NetPeer peer, int hashKey);
// 세션 정상 해제 시 호출 (재연결 교체 시에는 호출되지 않음) // 세션 정상 해제 시 호출 (재연결 교체 시에는 호출되지 않음)
protected abstract void OnSessionDisconnected(NetPeer peer, long hashKey, DisconnectInfo info); protected abstract void OnSessionDisconnected(NetPeer peer, int hashKey, DisconnectInfo info);
// 인증된 피어의 게임 패킷 수신 / payload는 헤더 제거된 raw bytes → 실행 프로젝트에서 protobuf 역직렬화 // 인증된 피어의 게임 패킷 수신 / payload는 헤더 제거된 raw bytes → 실행 프로젝트에서 protobuf 역직렬화
protected abstract void HandlePacket(NetPeer peer, long hashKey, ushort type, byte[] payload); protected abstract void HandlePacket(NetPeer peer, int hashKey, ushort type, byte[] payload);
} }

View File

@@ -10,31 +10,35 @@ public class Session
set; set;
} }
public long HashKey public int HashKey
{ {
get; get;
init; init;
} }
public string UserName
{
get;
set;
}
public NetPeer Peer public NetPeer Peer
{ {
get; get;
set; set;
} }
// ─── 패킷 레이트 리미팅 ─────────────────────────── // 패킷 레이트 리미팅
private int packetCount; private int packetCount;
private long windowStartTicks; private long windowStartTicks;
/// <summary>초당 허용 패킷 수</summary> // 초당 허용 패킷 수
public int MaxPacketsPerSecond { get; set; } public int MaxPacketsPerSecond { get; set; }
/// <summary>연속 초과 횟수</summary> // 연속 초과 횟수
public int RateLimitViolations { get; private set; } public int RateLimitViolations { get; private set; }
/// <summary> // 패킷 수신 시 호출. 초당 제한 초과 시 true 반환.
/// 패킷 수신 시 호출. 초당 제한 초과 시 true 반환.
/// </summary>
public bool CheckRateLimit() public bool CheckRateLimit()
{ {
long now = Environment.TickCount64; long now = Environment.TickCount64;
@@ -57,13 +61,13 @@ public class Session
return false; return false;
} }
/// <summary>위반 카운트 초기화</summary> // 위반 카운트 초기화
public void ResetViolations() public void ResetViolations()
{ {
RateLimitViolations = 0; RateLimitViolations = 0;
} }
public Session(long hashKey, NetPeer peer, int maxPacketsPerSecond = 60) public Session(int hashKey, NetPeer peer, int maxPacketsPerSecond = 60)
{ {
HashKey = hashKey; HashKey = hashKey;
Peer = peer; Peer = peer;

View File

@@ -1,4 +1,3 @@
using System.Diagnostics;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using Serilog; using Serilog;
@@ -6,19 +5,22 @@ using Serilog;
namespace ServerLib.Utils; namespace ServerLib.Utils;
/// <summary> /// <summary>
/// 릴리즈 빌드 크래시 덤프 핸들러 /// 크래시 핸들러 (Windows / Linux 공통)
/// Register() 를 Program.cs 최상단에서 한 번 호출.
/// ///
/// Register() 를 Program.cs 최상단에서 한 번 호출. /// 덤프 생성은 CLR 환경변수로 처리 (스택 언와인드 전에 찍힘):
/// DOTNET_DbgEnableMiniDump=1
/// DOTNET_DbgMiniDumpType=4
/// DOTNET_DbgMiniDumpName=crashes/crash_%p_%t.dmp
/// ///
/// 생성 파일 (crashes/ 폴더): /// 생성 파일 (crashes/ 폴더):
/// Debug : crash_YYYY-MM-DD_HH-mm-ss.log /// crash_YYYY-MM-DD_HH-mm-ss.log ← 항상 생성
/// Release : crash_YYYY-MM-DD_HH-mm-ss.log /// crash_%p_%t.dmp ← CLR이 직접 생성 (정확한 크래시 위치)
/// crash_YYYY-MM-DD_HH-mm-ss.dmp ← 메모리 덤프 추가
/// </summary> /// </summary>
public static class CrashDumpHandler public static class CrashDumpHandler
{ {
private const string CRASH_DIR = "crashes"; private const string CRASH_DIR = "crashes";
private static int registered = 0; private static int registered;
public static void Register() public static void Register()
{ {
@@ -39,16 +41,13 @@ public static class CrashDumpHandler
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{ {
Exception? ex = e.ExceptionObject as Exception; Exception? ex = e.ExceptionObject as Exception;
bool isTerminating = e.IsTerminating; string tag = $"[CrashDump] UnhandledException (IsTerminating={e.IsTerminating})";
string tag = $"[CrashDump] UnhandledException (IsTerminating={isTerminating})";
WriteCrash(tag, ex); WriteCrash(tag, ex);
} }
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e) private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
{ {
e.SetObserved(); // 프로세스 종료 방지 e.SetObserved(); // 프로세스 종료 방지
string tag = "[CrashDump] UnobservedTaskException"; string tag = "[CrashDump] UnobservedTaskException";
WriteCrash(tag, e.Exception); WriteCrash(tag, e.Exception);
} }
@@ -62,25 +61,14 @@ public static class CrashDumpHandler
Directory.CreateDirectory(CRASH_DIR); Directory.CreateDirectory(CRASH_DIR);
string timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"); string timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
string basePath = Path.Combine(CRASH_DIR, $"crash_{timestamp}"); string logPath = Path.Combine(CRASH_DIR, $"crash_{timestamp}.log");
// 1. 크래시 로그 작성
string logPath = $"{basePath}.log";
WriteCrashLog(logPath, ex); WriteCrashLog(logPath, ex);
Log.Fatal("{Tag} → {Log}", tag, logPath); Log.Fatal("{Tag} → {Log}", tag, logPath);
#if !DEBUG
// 2. 메모리 덤프 작성 (Release only)
string dmpPath = $"{basePath}.dmp";
WriteDumpFile(dmpPath);
Log.Fatal("[CrashDump] 덤프 파일 저장 완료 → {Dmp}", dmpPath);
#endif
} }
catch (Exception writeEx) catch (Exception writeEx)
{ {
// 덤프 저장 실패는 무시 (이미 크래시 중이므로) Log.Error(writeEx, "[CrashDump] 로그 저장 실패");
Log.Error(writeEx, "[CrashDump] 덤프 저장 실패");
} }
finally finally
{ {
@@ -96,21 +84,18 @@ public static class CrashDumpHandler
sb.AppendLine("═══════════════════════════════════════════════════"); sb.AppendLine("═══════════════════════════════════════════════════");
sb.AppendLine(); sb.AppendLine();
// 환경 정보
sb.AppendLine("[Environment]"); sb.AppendLine("[Environment]");
sb.AppendLine($" OS : {RuntimeInformation.OSDescription}"); sb.AppendLine($" OS : {RuntimeInformation.OSDescription}");
sb.AppendLine($" Runtime : {RuntimeInformation.FrameworkDescription}"); sb.AppendLine($" Runtime : {RuntimeInformation.FrameworkDescription}");
sb.AppendLine($" PID : {Environment.ProcessId}"); sb.AppendLine($" PID : {Environment.ProcessId}");
sb.AppendLine($" WorkDir : {Environment.CurrentDirectory}"); sb.AppendLine($" WorkDir : {Environment.CurrentDirectory}");
sb.AppendLine($" MachineName: {Environment.MachineName}"); sb.AppendLine($" MachineName: {Environment.MachineName}");
sb.AppendLine(); sb.AppendLine();
// 스레드 정보
sb.AppendLine("[Thread]"); sb.AppendLine("[Thread]");
sb.AppendLine($" ThreadId : {Environment.CurrentManagedThreadId}"); sb.AppendLine($" ThreadId : {Environment.CurrentManagedThreadId}");
sb.AppendLine(); sb.AppendLine();
// 예외 정보
sb.AppendLine("[Exception]"); sb.AppendLine("[Exception]");
if (ex is null) if (ex is null)
{ {
@@ -118,7 +103,7 @@ public static class CrashDumpHandler
} }
else else
{ {
AppendException(sb, ex, depth: 0); AppendException(sb, ex, 0);
} }
File.WriteAllText(path, sb.ToString(), Encoding.UTF8); File.WriteAllText(path, sb.ToString(), Encoding.UTF8);
@@ -126,7 +111,7 @@ public static class CrashDumpHandler
private static void AppendException(StringBuilder sb, Exception ex, int depth) private static void AppendException(StringBuilder sb, Exception ex, int depth)
{ {
string indent = new string(' ', depth * 2); string indent = new(' ', depth * 2);
sb.AppendLine($"{indent} Type : {ex.GetType().FullName}"); sb.AppendLine($"{indent} Type : {ex.GetType().FullName}");
sb.AppendLine($"{indent} Message : {ex.Message}"); sb.AppendLine($"{indent} Message : {ex.Message}");
sb.AppendLine($"{indent} Source : {ex.Source}"); sb.AppendLine($"{indent} Source : {ex.Source}");
@@ -157,40 +142,4 @@ public static class CrashDumpHandler
AppendException(sb, ex.InnerException, depth + 1); AppendException(sb, ex.InnerException, depth + 1);
} }
} }
#if !DEBUG
// Windows MiniDumpWriteDump P/Invoke
[DllImport("dbghelp.dll", SetLastError = true)]
private static extern bool MiniDumpWriteDump(
IntPtr hProcess, uint processId, IntPtr hFile,
uint dumpType, IntPtr exceptionParam,
IntPtr userStreamParam, IntPtr callbackParam);
private const uint MiniDumpWithFullMemory = 0x00000002;
private static void WriteDumpFile(string path)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Log.Warning("[CrashDump] 덤프 생성은 Windows만 지원");
return;
}
using Process process = Process.GetCurrentProcess();
using FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
bool success = MiniDumpWriteDump(
process.Handle,
(uint)process.Id,
fs.SafeFileHandle.DangerousGetHandle(),
MiniDumpWithFullMemory,
IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
if (!success)
{
int err = Marshal.GetLastWin32Error();
Log.Error("[CrashDump] MiniDumpWriteDump 실패 (Win32 Error={Err})", err);
}
}
#endif
} }

View File

@@ -7,4 +7,20 @@
ports: ports:
- "9050:9050/udp" # LiteNetLib UDP 포트 - "9050:9050/udp" # LiteNetLib UDP 포트
- "9500:9500/udp" # LiteNetLib UDP 포트 - "9500:9500/udp" # LiteNetLib UDP 포트
- "40001:9500/udp" # LiteNetLib UDP 포트
- "40002:9500/udp" # LiteNetLib UDP 포트
- "40003:9500/udp" # LiteNetLib UDP 포트
- "40004:9500/udp" # LiteNetLib UDP 포트
- "40005:9500/udp" # LiteNetLib UDP 포트
- "40006:9500/udp" # LiteNetLib UDP 포트
- "40007:9500/udp" # LiteNetLib UDP 포트
- "40008:9500/udp" # LiteNetLib UDP 포트
- "40009:9500/udp" # LiteNetLib UDP 포트
- "40100:9500/udp" # LiteNetLib UDP 포트
environment:
- DOTNET_DbgEnableMiniDump=1 # 크래시 시 덤프 자동 생성
- DOTNET_DbgMiniDumpType=4 # 4 = Full dump
- DOTNET_DbgMiniDumpName=/app/crashes/crash_%p_%t.dmp
volumes:
- ./crashes:/app/crashes # 덤프/로그 로컬 마운트
restart: unless-stopped restart: unless-stopped