3 Commits

Author SHA1 Message Date
f27cee05bb fix: merge conflict 해결 — BossRaid 토큰 Dictionary 처리 및 개별 전송
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 12:55:25 +09:00
f9db0d26ca fix: BossRaid 토큰 처리 수정 및 merge conflict 해결
- RestApi.cs: Tokens를 Dictionary<string, string>?으로 수정
- BossRaidResult.cs: Tokens를 Dictionary<string, string>?으로 수정
- GameServer.cs: SendTo(peer) → SendTo(memberPeer) 버그 수정,
  각 파티원에게 개별 토큰 전송

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 12:49:14 +09:00
46dd92b27d feat: 보스레이드 연동 — 입장 요청, 토큰 검증, 결과 보고 API 추가
- RestApi에 보스레이드 입장/검증/시작/완료/실패 엔드포인트 추가
- GameServer에 보스레이드 흐름 처리 로직
- Player 모델에 보스레이드 상태 필드 추가
- 보스레이드 관련 패킷 정의

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 17:51:33 +09:00
6 changed files with 346 additions and 57 deletions

182
CLAUDE.md Normal file
View File

@@ -0,0 +1,182 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Commands
```bash
# 서버 빌드 및 실행
cd MMOTestServer
dotnet build -c Debug
dotnet run --project MMOserver/MMOserver.csproj
# 릴리즈 빌드
dotnet build -c Release
dotnet publish -c Release
# Docker
cd MMOTestServer
docker-compose up --build # 9050/udp, 9500/udp 노출
# 클라이언트 테스터
cd ClientTester/EchoClientTester
dotnet run # 대화형 메뉴
dotnet run -- stress -c 100 -d 60 # 부하 테스트
dotnet run -- stress -c 50 -d 0 -i 100 -r 1000 -b 10 # 상세 옵션
```
## Tech Stack
- **C# / .NET 9.0** (C# 13)
- **LiteNetLib** — UDP 네트워킹
- **protobuf-net** — 바이너리 패킷 직렬화
- **MySQL** + **Dapper** / **Dapper.Contrib** — 비동기 DB 접근
- **Serilog** — 로깅 (콘솔 + 파일)
## Project Purpose
"One of the plans" 게임의 실시간 MMO 서버.
로비, 채널 관리, 플레이어 동기화 (이동/전투/상태) 담당.
## Project Structure
```
MMOTestServer/
├── MMOserver/ # 게임 서버 실행 프로젝트
│ ├── Game/ # GameServer, Player, Channel, ChannelManager
│ ├── Packet/ # PacketHeader(코드 정의), PacketBody(Protobuf 메시지)
│ ├── Api/ # RestApi (JWT 검증 외부 호출)
│ ├── RDB/ # Handler → Service → Repository → MySQL
│ ├── Utils/ # UuidGeneratorManager, Singleton
│ ├── Program.cs # 진입점
│ ├── config.json # DB 연결 설정
│ └── Dockerfile # 멀티스테이지 빌드
├── ServerLib/ # 재사용 네트워킹 DLL
│ ├── Service/ # ServerBase, Session, SessionManager
│ ├── Packet/ # PacketSerializer
│ └── RDB/ # ARepository<T>, DbConnectionFactory
└── compose.yaml # Docker Compose
ClientTester/
└── EchoClientTester/ # 테스트 클라이언트
├── EchoDummyService/ # Echo RTT 측정
├── DummyService/ # 더미 플레이어 이동 시뮬레이션 (10명)
└── StressTest/ # 부하 테스트 (P50/P95/P99, CSV 내보내기)
```
## 핵심 아키텍처
### 네트워크 코어 (ServerLib)
**ServerBase** — LiteNetLib `INetEventListener` 구현. 싱글 스레드 이벤트 폴링 (1ms 간격).
연결 흐름:
```
UDP Connect → PendingPeer 등록 → 인증 패킷 수신 → Session 생성 → OnSessionConnected
```
- **PendingPeers**: `Dictionary<int, NetPeer>` (peer.Id 기반, 미인증)
- **Sessions**: `Dictionary<long, Session>` (hashKey 기반, 인증 완료)
- **TokenHash**: `Dictionary<string, long>` (JWT 토큰 → hashKey 매핑)
- **재접속**: 같은 hashKey로 재접속 시 기존 peer 교체 (WiFi↔LTE 전환 대응)
- **전송 헬퍼**: `SendTo()`, `Broadcast()`, `BroadcastExcept()` (캐시된 NetDataWriter 사용)
**Session** — 연결별 상태: Token, HashKey, Peer 참조.
- 속도 제한: 슬라이딩 윈도우 (1초), 기본 60 패킷/초
- 3회 위반 시 강제 연결 해제
### 패킷 프로토콜
바이너리 헤더 + Protobuf 페이로드:
```
[2B: type (ushort LE)] [2B: size (ushort LE)] [NB: protobuf payload]
```
**패킷 코드 (PacketHeader.cs):**
| 코드 | 이름 | 전송 방식 | 용도 |
|------|------|-----------|------|
| 1 | ACC_TOKEN | Reliable | JWT 인증 |
| 1001 | DUMMY_ACC_TOKEN | Reliable | 테스트 인증 (hashKey≤1000) |
| 1000 | ECHO | ReliableUnordered | RTT 측정 |
| 2 | LOAD_GAME | Reliable | 게임 로드 |
| 3 | LOAD_CHANNEL | Reliable | 채널 목록 |
| 4 | INTO_CHANNEL | Reliable | 채널 입장 |
| 5 | UPDATE_CHANNEL_USER | Reliable | 유저 입장/퇴장 브로드캐스트 |
| 6 | EXIT_CHANNEL | Reliable | 채널 퇴장 |
| 7 | TRANSFORM_PLAYER | **Unreliable** | 위치/회전 동기화 (HOL 방지) |
| 8 | ACTION_PLAYER | ReliableOrdered | 공격/스킬/회피 액션 |
| 9 | STATE_PLAYER | ReliableOrdered | HP/MP 상태 |
| 10-12 | TRANSFORM/ACTION/STATE_NPC | 위와 동일 | NPC 동기화 |
| 13 | DAMAGE | Reliable | 데미지 |
| 14-15 | UPDATE_PARTY/USER_PARTY | Reliable | 파티 |
**Protobuf 메시지 (PacketBody.cs):**
- PlayerInfo: PlayerId, Nickname, Level, Hp, MaxHp, Mp, MaxMp, Position(Vector3), RotY
- TransformPlayerPacket: PlayerId, Position, RotY
- ActionPlayerPacket: PlayerId, PlayerActionType(IDLE/MOVE/ATTACK/SKILL/DODGE/DIE/REVIVE), SkillId, TargetId
- StatePlayerPacket: PlayerId, Hp, MaxHp, Mp, MaxMp
### GameServer (MMOserver/Game/)
ServerBase 확장. 패킷 핸들러 딕셔너리로 라우팅:
- `INTO_CHANNEL` — 채널 입장, 기존 유저 목록 응답 + 신규 유저 브로드캐스트
- `EXIT_CHANNEL` — 채널 퇴장, 나머지 유저에게 알림
- `TRANSFORM_PLAYER` — 위치 브로드캐스트 (Unreliable)
- `ACTION_PLAYER` — 액션 브로드캐스트 (ReliableOrdered)
- `STATE_PLAYER` — 상태 브로드캐스트 (ReliableOrdered)
**인증 흐름:**
- `HandleAuth()`: JWT를 `https://a301.api.tolelom.xyz/api/auth/verify`로 검증 (3회 재시도, 5초 타임아웃). 401이면 즉시 실패.
- `HandleAuthDummy()`: 토큰 값을 hashKey로 직접 사용 (hashKey≤1000만 허용).
### 채널 시스템
- **Channel**: `Dictionary<long, Player>` (hashKey → Player). 기본 최대 100명.
- **ChannelManager**: 싱글톤. 기본 1개 채널. `connectUsers` 딕셔너리로 userId→channelId 추적.
### DB 레이어
**Handler → Service → Repository → MySQL** 패턴.
- **ARepository\<T\>**: Dapper.Contrib 기반 제네릭 CRUD. 트랜잭션 지원 (`WithTransactionAsync`).
- **DbConnectionFactory**: `config.json` 또는 환경변수에서 연결 문자열 생성. 커넥션 풀: Min=5, Max=100.
- **Response\<T\>**: 표준 응답 봉투 (`{ Success, Data, Error }`).
새 테이블 추가 시: `Models/``Repositories/` (ARepository 상속) → `Services/``Handlers/`. ServerLib은 수정 불필요.
## 스레딩 모델
- 네트워크 루프: 싱글 스레드 폴링 (게임 상태에 락 불필요)
- JWT 검증 / DB: async/await (네트워크 루프 블로킹 없음)
- UUID 생성: ReaderWriterLockSlim
## 설정
```json
// config.json
{
"Database": {
"Host": "localhost",
"Port": "3306",
"Name": "game_db",
"User": "root",
"Password": "...",
"Pooling": {
"MinimumPoolSize": "5",
"MaximumPoolSize": "100",
"ConnectionTimeout": "30",
"ConnectionIdleTimeout": "180"
}
}
}
```
서버 기본 포트: 9500 (UDP). Ping 간격: 3000ms. 연결 타임아웃: 60000ms.
## 알려진 제한사항
- 서버 측 위치 검증 미구현 (스피드핵/텔레포트 가능)
- 플레이어 데이터 DB 영속화 미구현 (하드코딩된 기본값 사용)
- NPC/파티 패킷 코드 정의됨 but 핸들러 미구현
- 수평 확장 미지원 (단일 서버 인스턴스)

View File

@@ -4,39 +4,10 @@ namespace MMOserver.Api;
// 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;
} = new();
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

@@ -59,6 +59,38 @@ public class RestApi : Singleton<RestApi>
return "";
}
// 플레이어 프로필 조회 - 성공 시 PlayerProfileResponse 반환
public async Task<PlayerProfileResponse?> GetPlayerProfileAsync(string username)
{
string url = VERIFY_URL + "/api/internal/player/profile?username=" + Uri.EscapeDataString(username);
for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
{
try
{
HttpResponseMessage response = await httpClient.GetAsync(url);
if (response.StatusCode == HttpStatusCode.NotFound)
{
Log.Warning("[RestApi] 프로필 없음 username={Username}", username);
return null;
}
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<PlayerProfileResponse>();
}
catch (Exception ex) when (attempt < MAX_RETRY)
{
Log.Warning("[RestApi] 프로필 조회 실패 (시도 {Attempt}/{Max}): {Message}", attempt, MAX_RETRY, ex.Message);
await Task.Delay(RETRY_DELAY);
}
catch (Exception ex)
{
Log.Error("[RestApi] 프로필 조회 최종 실패 ({Max}회 시도): {Message}", MAX_RETRY, ex.Message);
}
}
return null;
}
private sealed class AuthVerifyResponse
{
[JsonPropertyName("username")]
@@ -69,6 +101,36 @@ public class RestApi : Singleton<RestApi>
}
}
public sealed class PlayerProfileResponse
{
[JsonPropertyName("nickname")]
public string Nickname { get; set; } = string.Empty;
[JsonPropertyName("level")]
public int Level { get; set; }
[JsonPropertyName("experience")]
public int Experience { get; set; }
[JsonPropertyName("nextExp")]
public int NextExp { get; set; }
[JsonPropertyName("maxHp")]
public double MaxHp { get; set; }
[JsonPropertyName("maxMp")]
public double MaxMp { get; set; }
[JsonPropertyName("attackPower")]
public double AttackPower { get; set; }
[JsonPropertyName("attackRange")]
public double AttackRange { get; set; }
[JsonPropertyName("sprintMultiplier")]
public double SprintMultiplier { get; set; }
}
// 레이드 채널 접속 여부 체크
// 성공 시 BossRaidResult 반환, 실패/거절 시 null 반환
public async Task<BossRaidResult?> BossRaidAccesssAsync(List<string> userNames, int bossId)
@@ -166,7 +228,7 @@ public class RestApi : Singleton<RestApi>
}
[JsonPropertyName("tokens")]
public Dictionary<string, string> Tokens
public Dictionary<string, string>? Tokens
{
get;
set;

View File

@@ -103,7 +103,7 @@ public class GameServer : ServerBase
{
AccTokenPacket accTokenPacket = Serializer.Deserialize<AccTokenPacket>(new ReadOnlyMemory<byte>(payload));
string token = accTokenPacket.Token;
string? username = "";
string? verifiedUsername = null;
tokenHash.TryGetValue(token, out int hashKey);
if (hashKey <= 1000)
{
@@ -121,7 +121,7 @@ public class GameServer : ServerBase
else
{
// 신규 연결: 웹서버에 JWT 검증 요청
username = await RestApi.Instance.VerifyTokenAsync(token);
string? username = await RestApi.Instance.VerifyTokenAsync(token);
if (username == null || username.Trim().Length <= 0)
{
Log.Warning("[Server] 토큰 검증 실패 - 연결 거부 PeerId={Id}", peer.Id);
@@ -131,15 +131,16 @@ public class GameServer : ServerBase
}
Log.Information("[Server] 토큰 검증 성공 Username={Username} PeerId={Id}", username, peer.Id);
verifiedUsername = username;
}
peer.Tag = new Session(hashKey, peer);
((Session)peer.Tag).Token = token;
if (username.Length > 0)
if (verifiedUsername != null)
{
((Session)peer.Tag).UserName = username;
((Session)peer.Tag).Username = verifiedUsername;
((Session)peer.Tag).UserName = verifiedUsername;
}
sessions[hashKey] = peer;
tokenHash[token] = hashKey;
pendingPeers.Remove(peer.Id);
@@ -406,7 +407,12 @@ public class GameServer : ServerBase
Mp = player.Mp,
MaxMp = player.MaxMp,
Position = new Position { X = player.PosX, Y = player.PosY, Z = player.PosZ },
RotY = player.RotY
RotY = player.RotY,
Experience = player.Experience,
NextExp = player.NextExp,
AttackPower = player.AttackPower,
AttackRange = player.AttackRange,
SprintMultiplier = player.SprintMultiplier,
};
}
@@ -414,7 +420,7 @@ public class GameServer : ServerBase
// 패킷 핸들러
// ============================================================
private void OnIntoChannel(NetPeer peer, int hashKey, byte[] payload)
private async void OnIntoChannel(NetPeer peer, int hashKey, byte[] payload)
{
IntoChannelPacket packet = Serializer.Deserialize<IntoChannelPacket>(new ReadOnlyMemory<byte>(payload));
@@ -453,15 +459,50 @@ public class GameServer : ServerBase
return;
}
// TODO: 실제 서비스에서는 DB/세션에서 플레이어 정보 로드 필요
Player newPlayer = new()
// API 서버에서 플레이어 프로필 로드
Player newPlayer = new Player
{
HashKey = hashKey,
PlayerId = hashKey,
Nickname = ((Session)peer.Tag).UserName
};
// 채널에 추가
Session? session = peer.Tag as Session;
string? username = session?.Username;
if (!string.IsNullOrEmpty(username))
{
try
{
RestApi.PlayerProfileResponse? profile = await RestApi.Instance.GetPlayerProfileAsync(username);
if (profile != null)
{
newPlayer.Nickname = string.IsNullOrEmpty(profile.Nickname) ? username : profile.Nickname;
newPlayer.Level = profile.Level;
newPlayer.MaxHp = (int)profile.MaxHp;
newPlayer.Hp = (int)profile.MaxHp;
newPlayer.MaxMp = (int)profile.MaxMp;
newPlayer.Mp = (int)profile.MaxMp;
newPlayer.Experience = profile.Experience;
newPlayer.NextExp = profile.NextExp;
newPlayer.AttackPower = (float)profile.AttackPower;
newPlayer.AttackRange = (float)profile.AttackRange;
newPlayer.SprintMultiplier = (float)profile.SprintMultiplier;
Log.Information("[GameServer] 프로필 로드 완료 Username={Username} Level={Level} MaxHp={MaxHp}",
username, profile.Level, profile.MaxHp);
}
else
{
newPlayer.Nickname = username;
Log.Warning("[GameServer] 프로필 로드 실패 — 기본값 사용 Username={Username}", username);
}
}
catch (Exception ex)
{
newPlayer.Nickname = username;
Log.Error(ex, "[GameServer] 프로필 로드 예외 Username={Username}", username);
}
}
cm.AddUser(packet.ChannelId, hashKey, newPlayer, peer);
Log.Debug("[GameServer] INTO_CHANNEL HashKey={Key} ChannelId={ChannelId}", hashKey, packet.ChannelId);
@@ -1147,17 +1188,14 @@ public class GameServer : ServerBase
SendTo(memberPeer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
// 모두에게 레이드로 이동 (할당된 실제 레이드 맵 ID 전달)
if (result.Tokens.ContainsKey(memberPlayer.Nickname.Trim()))
{
SendTo(peer,
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket
{
RaidId = assignedRaidMapId, IsSuccess = true, Session = result.SessionName,
Token = result.Tokens[memberPlayer.Nickname.Trim()]
}));
}
// 각 멤버에게 개별 토큰과 함께 레이드 이동 알림
string? memberToken = null;
result.Tokens?.TryGetValue(memberPlayer.Nickname, out memberToken);
SendTo(memberPeer,
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket
{ RaidId = assignedRaidMapId, IsSuccess = true, Session = result.SessionName, Token = memberToken }));
}
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId}", hashKey, party.PartyId,

View File

@@ -50,6 +50,36 @@ public class Player
set;
}
public int Experience
{
get;
set;
}
public int NextExp
{
get;
set;
}
public float AttackPower
{
get;
set;
}
public float AttackRange
{
get;
set;
}
public float SprintMultiplier
{
get;
set;
}
// 위치/방향 (클라이언트 패킷과 동일하게 float)
public float PosX
{

View File

@@ -10,6 +10,12 @@ public class Session
set;
}
public string? Username
{
get;
set;
}
public int HashKey
{
get;