70 Commits

Author SHA1 Message Date
qornwh1
5221261d1e feat : 주석 업데이트 2026-03-30 17:29:57 +09:00
qornwh1
462f9d98f1 feat : 파일 정리 2026-03-30 14:29:13 +09:00
qornwh1
530f32420d feat : GameServer 패킷 메시지 단위 분할 / 플레이어 정보 변환 기능 변경 2026-03-30 14:29:02 +09:00
qornwh1
2ebd0120ab feat : 코드 주석 정리 2026-03-30 12:47:36 +09:00
qornwh1
849105f8ff feat : 더미 스폰 위치 정리 2026-03-30 12:29:41 +09:00
qornwh1
0617e6a194 feat : 코드 단락 정리 2026-03-30 12:29:20 +09:00
qornwh1
ca5a345c8f feat : 더미 이동 높이 조절 2026-03-26 17:03:38 +09:00
cfc242f248 Fix: 보스 레이드 입장 시 503 응답 처리 추가
- BossRaidAccessAsync에서 ServiceUnavailable(503) 응답도 입장 거절로 처리
- 기존에는 503이 예외로 빠져 불필요한 3회 재시도 후 실패

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 22:04:04 +09:00
0f1ee36794 Fix: 보스 레이드 입장 실패 시 구체적 사유 전달
IntoBossRaidPacket에 Reason 필드 추가.
파티 없음, 파티장 아님, API 실패 등 실패 사유를
클라이언트에 전달하여 유저에게 안내.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 11:00:51 +09:00
64855c5a69 Fix: 플레이어 프로필 DB 연동, 파티 초대/추방 프로토콜 구현
- 채널 입장 시 API 서버에서 플레이어 프로필 로드 (레벨/스탯/위치)
- 채널 퇴장 시 위치/플레이타임 DB 저장 (SaveGameDataAsync)
- Player.cs에 AttackPower/AttackRange/SprintMultiplier/Experience 필드 추가
- ToPlayerInfo에서 전투 스탯 매핑 추가
- Session에 ChannelJoinedAt 추가 (플레이타임 계산용)
- PartyUpdateType에 INVITE/KICK 추가
- RequestPartyPacket에 TargetPlayerId 필드 추가
- GameServer에 INVITE/KICK 핸들러 구현
- Channel에 GetPeer() 메서드 추가
- RestApi에 GetPlayerProfileAsync/SaveGameDataAsync 추가

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 21:10:05 +09:00
qornwh1
f77219e9d2 fix : 더미 클라 패킷 정리 2026-03-19 17:42:32 +09:00
qornwh1
4493729519 fix : 로그 수정 2026-03-19 10:42:36 +09:00
qornwh1
48c9f1031b fix : 서버 버그 수정 작업 머지
Merge branch 'fix/mmo-server-logic-bugs' of https://git.tolelom.xyz/A301/a301_mmo_game_server

# Conflicts:
#	MMOTestServer/MMOserver/Game/GameServer.cs
2026-03-19 09:12:18 +09:00
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
qornwh1
9a155fa056 feat : 보스맵 종료후 -> 로비 맵 이동 처리 2026-03-17 14:28:39 +09:00
qornwh1
1c63b8532f fix : 코드 버그 수정 2026-03-17 12:58:04 +09:00
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
qornwh1
fb76f49ec0 feat : 보스 전용채널 제거, 채널 5개로 변경, config.json 정리 2026-03-17 10:33:08 +09:00
qornwh1
f8fa34edbc feat : 보스 응답 메시지 문제 수정 2026-03-17 09:15:41 +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
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
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
qornwh1
c27e8464b4 fix : 채널 버그 수정 2026-03-05 16:34:52 +09:00
qornwh1
d4c5a70a39 fix : 채널 버그 수정 2026-03-05 16:34:33 +09:00
qornwh1
ea3f64a40d feat : 스트레스 테스트 기능 추가 / 패킷 처리량 제한 / 프로젝트 상황 리드미 추가 2026-03-05 10:58:49 +09:00
qornwh1
2be1302b24 feat : 덤프 남기는 기능 추가 (셋팅값 힙 덤프) 2026-03-04 17:29:36 +09:00
qornwh1
42f0ef14f2 fix : 이동패킷은 재전송 하지 않도록 변경 2026-03-04 17:04:46 +09:00
qornwh1
bfa3394ad1 feat : 토큰 -> 해시키 생성 로직 구조 변경 / 토큰 관리 로직 추가 2026-03-04 16:51:44 +09:00
qornwh1
c8ce36a624 feat : 로그인 실패시 재시도 로직 추가 2026-03-04 16:12:45 +09:00
qornwh1
18fd8a0737 fix : 에코 클라이언트 수신 버그 수정 2026-03-04 16:02:22 +09:00
qornwh1
343ea43a03 feat : 토큰 인증 RestApi 구현 / Token기반 haskKey구현 / Dummy, User Token체크 분기 2026-03-04 15:53:15 +09:00
qornwh1
053c5d23b9 feat : 맵 바운딩 박스 처리 / echo 패킷 구조 재 구성 / 더미 클라이언트 랜덤 이동 작업 2026-03-04 14:51:43 +09:00
qornwh1
241820846d feat : 1번(토큰 받기) 패킷 수정 2026-03-04 10:57:58 +09:00
58 changed files with 6091 additions and 630 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

@@ -11,10 +11,18 @@ public class DummyClientService
// 모든거 강종
public event Action? OnAllDisconnected;
public DummyClientService(int count, string ip, int port, string key, int sendIntervalMs = 1000)
public DummyClientService(int count, string ip, int port, string key, int sendIntervalMs = 1000, MapBounds? mapBounds = null)
{
sendInterval = sendIntervalMs;
clients = Enumerable.Range(1, count + 1).Select(i => new DummyClients(i, ip, port, key)).ToList();
clients = Enumerable.Range(1, count).Select(i =>
{
DummyClients client = new DummyClients(i, ip, port, key);
if (mapBounds != null)
{
client.Map = mapBounds;
}
return client;
}).ToList();
Log.Information("[SERVICE] {Count}개 클라이언트 생성 → {Ip}:{Port}", count, ip, port);
}
@@ -30,30 +38,23 @@ public class DummyClientService
{
foreach (DummyClients c in clients)
{
c.PollEvents();
}
try
{
await Task.Delay(10, ct);
c.PollEvents();
}
catch (OperationCanceledException)
catch (Exception ex)
{
break;
Log.Error("[Client {ClientId}] PollEvents 예외: {Ex}", c.clientId, ex.Message);
}
}
await Task.Delay(10);
}
}
private async Task SendLoopAsync(CancellationToken ct)
{
try
{
await Task.Delay(500, ct);
}
catch (OperationCanceledException)
{
return;
}
await Task.Delay(500);
int tick = 0;
@@ -85,14 +86,7 @@ public class DummyClientService
Log.Debug("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total);
tick++;
try
{
await Task.Delay(sendInterval, ct);
}
catch (OperationCanceledException)
{
break;
}
await Task.Delay(sendInterval);
}
}

View File

@@ -12,7 +12,7 @@ public class DummyClients
private EventBasedNetListener listener;
private NetDataWriter? writer;
public NetPeer? peer;
public long clientId; // 일단 이게 hashKey가 됨 => 0 ~ 1000번까지는 더미용응로 뺴둠
public int clientId; // 일단 이게 hashKey가 됨 => 0 ~ 1000번까지는 더미용응로 뺴둠
// info
private Vector3 position = new Vector3();
@@ -28,6 +28,9 @@ public class DummyClients
private float dirX = 0f;
private float dirZ = 0f;
// 맵 경계
public MapBounds Map { get; set; } = new MapBounds(-95f, -25f, -30f, 10f);
// 통계
public int SentCount
{
@@ -47,7 +50,7 @@ public class DummyClients
get;
}
public DummyClients(long clientId, string ip, int port, string key)
public DummyClients(int clientId, string ip, int port, string key)
{
this.clientId = clientId;
listener = new EventBasedNetListener();
@@ -60,10 +63,10 @@ public class DummyClients
Log.Information("[Client {ClientId:00}] 연결됨", this.clientId);
// clientID가 토큰의 hashKey라고 가정함
AccTokenPacket recvTokenPacket = new AccTokenPacket();
DummyAccTokenPacket recvTokenPacket = new DummyAccTokenPacket();
recvTokenPacket.Token = clientId;
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.ACC_TOKEN, recvTokenPacket);
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.DUMMY_ACC_TOKEN, recvTokenPacket);
writer.Put(data);
peer.Send(writer, DeliveryMethod.ReliableOrdered);
writer.Reset();
@@ -71,15 +74,6 @@ public class DummyClients
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();
};
@@ -92,6 +86,9 @@ public class DummyClients
manager.Start();
manager.Connect(ip, port, key);
position.X = -60;
position.Z = 25;
}
public void UpdateDummy()
@@ -104,8 +101,12 @@ public class DummyClients
// 남은 거리가 없으면 새 방향·목표 거리 설정
if (distance <= 0f)
{
// 현재 각도에서 -30~+30도 범위로 회전
rotY = (rotY + Random.Shared.Next(-30, 31) + 360) % 360;
// 벽에 붙어있으면 반대 방향 강제, 아니면 ±30도 회전
int wallRotY = Map.GetRotYAwayFromWall(posX, posZ);
rotY = wallRotY >= 0
? (wallRotY + Random.Shared.Next(-30, 31) + 360) % 360
: (rotY + Random.Shared.Next(-30, 31) + 360) % 360;
float rad = rotY * MathF.PI / 180f;
dirX = MathF.Sin(rad);
dirZ = MathF.Cos(rad);
@@ -117,13 +118,18 @@ public class DummyClients
// 이번 틱 이동량 (남은 거리 초과 방지)
float step = MathF.Min(moveSpeed * delta, distance);
posX += dirX * step;
posZ += dirZ * step;
distance -= step;
float nextX = posX + dirX * step;
float nextZ = posZ + dirZ * step;
// 벽 충돌 시 clamp + 다음 틱에 방향 재설정
bool hitWall = Map.Clamp(ref nextX, ref nextZ);
posX = nextX;
posZ = nextZ;
distance = hitWall ? 0f : distance - step;
// 정수 Vector3 갱신
position.X = (int)MathF.Round(posX);
position.Z = (int)MathF.Round(posZ);
position.X = posX;
position.Z = posZ;
}
public void SendTransform()
@@ -136,12 +142,12 @@ public class DummyClients
UpdateDummy();
TransformPlayerPacket transformPlayerPacket = new TransformPlayerPacket
{
PlayerId = (int)clientId,
PlayerId = clientId,
RotY = rotY,
Position = new Packet.Vector3
Position = new Packet.Position
{
X = position.X,
Y = 0, // 높이는 버린다.
Y = -3.7f, // 높이는 버린다.
Z = position.Z
}
};

View File

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

View File

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

View File

@@ -59,27 +59,13 @@ public class EchoDummyClientService
c.PollEvents();
}
try
{
await Task.Delay(10, ct);
}
catch (OperationCanceledException)
{
break;
}
await Task.Delay(10);
}
}
private async Task SendLoopAsync(CancellationToken ct)
{
try
{
await Task.Delay(500, ct);
}
catch (OperationCanceledException)
{
return;
}
await Task.Delay(500);
int tick = 0;
@@ -111,14 +97,7 @@ public class EchoDummyClientService
Log.Debug("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total);
tick++;
try
{
await Task.Delay(sendInterval, ct);
}
catch (OperationCanceledException)
{
break;
}
await Task.Delay(sendInterval);
}
}

View File

@@ -1,8 +1,10 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using ClientTester.Packet;
using LiteNetLib;
using LiteNetLib.Utils;
using ProtoBuf;
using Serilog;
namespace ClientTester.EchoDummyService;
@@ -75,10 +77,14 @@ public class EchoDummyClients
{
short code = reader.GetShort();
short bodyLength = reader.GetShort();
string? msg = reader.GetString();
byte[] payloadBytes = new byte[bodyLength];
reader.GetBytes(payloadBytes, bodyLength);
EchoPacket echoPacket = PacketSerializer.DeserializePayload<EchoPacket>(payloadBytes);
string msg = echoPacket.Str;
long sentTick;
if (msg != null && msg.StartsWith("Echo seq:") &&
if (msg.StartsWith("Echo seq:") &&
int.TryParse(msg.Substring("Echo seq:".Length), out int seq) &&
pendingPings.TryRemove(seq, out sentTick))
{
@@ -131,12 +137,12 @@ public class EchoDummyClients
}
}
PacketHeader packetHeader = new PacketHeader();
packetHeader.Code = 0;
packetHeader.BodyLength = (ushort)$"Echo seq:{seq}".Length;
writer.Put((short)packetHeader.Code);
writer.Put((short)packetHeader.BodyLength);
writer.Put($"Echo seq:{seq}");
// string → raw bytes (길이 prefix 방지)
EchoPacket echoPacket = new EchoPacket();
echoPacket.Str = $"Echo seq:{seq}";
byte[] data = PacketSerializer.Serialize<EchoPacket>((ushort)PacketCode.ECHO, echoPacket);
writer.Put(data);
// 순서보장 안함 HOL Blocking 제거
peer.Send(writer, DeliveryMethod.ReliableUnordered);
SentCount++;

View File

@@ -4,12 +4,28 @@ using ProtoBuf;
namespace ClientTester.Packet;
// ============================================================
// 에코용
// ============================================================
// ECHO
[ProtoContract]
public class EchoPacket
{
[ProtoMember(1)]
public string Str
{
get;
set;
}
}
// ============================================================
// 공통 타입
// ============================================================
[ProtoContract]
public class Vector3
public class Position
{
[ProtoMember(1)]
public float X
@@ -86,7 +102,7 @@ public class PlayerInfo
}
[ProtoMember(8)]
public Vector3 Position
public Position Position
{
get;
set;
@@ -98,18 +114,65 @@ public class PlayerInfo
get;
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;
}
}
// ============================================================
// 인증
// ============================================================
// DUMMY_ACC_TOKEN
[ProtoContract]
public class DummyAccTokenPacket
{
[ProtoMember(1)]
public int Token
{
get;
set;
}
}
// ACC_TOKEN
[ProtoContract]
public class AccTokenPacket
{
[ProtoMember(1)]
public long Token
public string Token
{
get;
set;
@@ -135,7 +198,7 @@ public class LoadGamePacket
}
[ProtoMember(3)]
public int MaplId
public int MapId
{
get;
set;
@@ -157,7 +220,7 @@ public class ChannelInfo
}
[ProtoMember(2)]
public int ChannelUserConut
public int ChannelUserCount
{
get;
set;
@@ -182,7 +245,42 @@ public class LoadChannelPacket
} = 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]
public class IntoChannelPacket
{
@@ -199,6 +297,47 @@ public class IntoChannelPacket
get;
set;
} = 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 유저 접속/나감
@@ -259,7 +398,7 @@ public class TransformPlayerPacket
}
[ProtoMember(2)]
public Vector3 Position
public Position Position
{
get;
set;
@@ -371,7 +510,7 @@ public class TransformNpcPacket
}
[ProtoMember(2)]
public Vector3 Position
public Position Position
{
get;
set;
@@ -488,6 +627,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;
}
}
// ============================================================
// 파티
// ============================================================
@@ -495,16 +660,195 @@ public class DamagePacket
public enum PartyUpdateType
{
CREATE,
DELETE
}
public enum UserPartyUpdateType
{
DELETE,
JOIN,
LEAVE
LEAVE,
UPDATE,
INVITE,
KICK
}
// 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]
public class UpdatePartyPacket
{
@@ -528,30 +872,18 @@ public class UpdatePartyPacket
get;
set;
}
}
// UPDATE_USER_PARTY
[ProtoContract]
public class UpdateUserPartyPacket
{
[ProtoMember(1)]
public int PartyId
{
get;
set;
}
[ProtoMember(2)]
[ProtoMember(4)]
public int PlayerId
{
get;
set;
}
[ProtoMember(3)]
public UserPartyUpdateType Type
[ProtoMember(5)]
public string PartyName
{
get;
set;
}
} // CREATE일 때 사용
}

View File

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

View File

@@ -11,7 +11,7 @@ namespace ClientTester.Packet
public static byte[] Serialize<T>(ushort type, T packet)
{
using MemoryStream payloadMs = new MemoryStream();
Serializer.Serialize(payloadMs, packet);
Serializer.Serialize<T>(payloadMs, packet);
byte[] payload = payloadMs.ToArray();
ushort size = (ushort)payload.Length;

View File

@@ -1,13 +1,30 @@
using System.Text.Json;
using ClientTester.DummyService;
using ClientTester.EchoDummyService;
using ClientTester.StressTest;
using ClientTester.Utils;
using Serilog;
class EcoClientTester
{
public static readonly string SERVER_IP = "localhost";
public static readonly int SERVER_PORT = 9500;
public static readonly string CONNECTION_KEY = "test";
public static readonly int CLIENT_COUNT = 100;
public static string SERVER_IP = "localhost";
public static int SERVER_PORT = 9500;
public static string CONNECTION_KEY = "";
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()
{
@@ -77,8 +94,84 @@ class EcoClientTester
}
}
private async Task StartStressTest(int duration, int sendInterval, int rampInterval, int clientsPerRamp)
{
try
{
CancellationTokenSource cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
Log.Warning("[SHUTDOWN] Ctrl+C 감지, 종료 중...");
cts.Cancel();
};
StressTestService service = new StressTestService(
CLIENT_COUNT, SERVER_IP, SERVER_PORT, CONNECTION_KEY,
durationSec: duration,
sendIntervalMs: sendInterval,
rampUpIntervalMs: rampInterval,
clientsPerRamp: clientsPerRamp);
service.OnTestCompleted += () =>
{
Log.Information("[STRESS] 테스트 시간 종료.");
};
try
{
await service.RunAsync(cts.Token);
}
catch (OperationCanceledException) { }
service.PrintFinalReport();
string timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
string csvPath = $"results/stress_{CLIENT_COUNT}clients_{timestamp}.csv";
Directory.CreateDirectory("results");
service.ExportCsv(csvPath);
service.Stop();
await Log.CloseAndFlushAsync();
}
catch (Exception e)
{
Log.Error($"[SHUTDOWN] 예외 발생 : {e}");
}
}
private static void PrintUsage()
{
Console.WriteLine();
Console.WriteLine("사용법:");
Console.WriteLine(" EchoClientTester 대화형 모드");
Console.WriteLine(" EchoClientTester stress [옵션] 스트레스 테스트");
Console.WriteLine();
Console.WriteLine("스트레스 테스트 옵션:");
Console.WriteLine(" -c, --clients <수> 클라이언트 수 (기본: 50)");
Console.WriteLine(" -d, --duration <초> 테스트 시간 (기본: 60, 0=무제한)");
Console.WriteLine(" -i, --interval <ms> 전송 주기 (기본: 100)");
Console.WriteLine(" -r, --ramp <ms> Ramp-up 간격 (기본: 1000)");
Console.WriteLine(" -b, --batch <수> Ramp-up 당 클라이언트 수 (기본: 10)");
Console.WriteLine(" --ip <주소> 서버 IP (기본: localhost)");
Console.WriteLine(" --port <포트> 서버 포트 (기본: 9500)");
Console.WriteLine();
Console.WriteLine("예시:");
Console.WriteLine(" EchoClientTester stress -c 100 -d 120");
Console.WriteLine(" EchoClientTester stress -c 200 -d 60 -r 500 -b 20 --ip 192.168.0.10");
}
private static async Task Main(string[] args)
{
// 유니코드 문자(═, ║ 등) 콘솔 깨짐 방지
Console.OutputEncoding = System.Text.Encoding.UTF8;
// appsettings.json 에서 설정 로드
LoadConfig();
// 크래시 덤프 핸들러 (Release: .log + .dmp / Debug: .log)
CrashDumpHandler.Register();
// .MinimumLevel.Warning() // Warning 이상만 출력 배포시
string timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
@@ -88,29 +181,95 @@ class EcoClientTester
.WriteTo.File($"logs2/log_{timestamp}.txt")
.CreateLogger();
Log.Information("========== 더미 클라 테스터 ==========");
Log.Information("1. 에코 서버");
Log.Information("2. 더미 클라(이동만)");
Log.Information("====================================");
Log.Information("1 / 2 : ");
EcoClientTester tester = new EcoClientTester();
string? input = Console.ReadLine();
if (!int.TryParse(input, out int choice) || (choice != 1 && choice != 2))
// CLI 모드: stress 명령
if (args.Length > 0 && args[0].Equals("stress", StringComparison.OrdinalIgnoreCase))
{
Log.Warning("1 또는 2만 입력하세요.");
// 기본값
// CLIENT_COUNT = 50;
int duration = 60;
int sendInterval = 100;
int rampInterval = 1000;
int clientsPerRamp = 10;
for (int i = 1; i < args.Length; i++)
{
switch (args[i])
{
case "-c": case "--clients":
if (i + 1 < args.Length) CLIENT_COUNT = int.Parse(args[++i]);
break;
case "-d": case "--duration":
if (i + 1 < args.Length) duration = int.Parse(args[++i]);
break;
case "-i": case "--interval":
if (i + 1 < args.Length) sendInterval = int.Parse(args[++i]);
break;
case "-r": case "--ramp":
if (i + 1 < args.Length) rampInterval = int.Parse(args[++i]);
break;
case "-b": case "--batch":
if (i + 1 < args.Length) clientsPerRamp = int.Parse(args[++i]);
break;
case "--ip":
if (i + 1 < args.Length) SERVER_IP = args[++i];
break;
case "--port":
if (i + 1 < args.Length) SERVER_PORT = int.Parse(args[++i]);
break;
case "-h": case "--help":
PrintUsage();
return;
}
}
await tester.StartStressTest(duration, sendInterval, rampInterval, clientsPerRamp);
return;
}
// CLI 모드: help
if (args.Length > 0 && (args[0] == "-h" || args[0] == "--help"))
{
PrintUsage();
return;
}
// 대화형 모드 (기존)
Log.Information("========== 더미 클라 테스터 ==========");
Log.Information("1. 에코 서버");
Log.Information("2. 더미 클라(이동만)");
Log.Information("3. 스트레스 테스트 (부하)");
Log.Information("====================================");
Log.Information("1 / 2 / 3 : ");
string? input = Console.ReadLine();
if (!int.TryParse(input, out int choice) || choice < 1 || choice > 3)
{
Log.Warning("1, 2, 3 중 입력하세요.");
return;
}
EcoClientTester tester = new EcoClientTester();
if (choice == 1)
{
// 에코 서버 실행
await tester.StartEchoDummyTest();
}
else if (choice == 2)
{
// 더미 클라 실행
await tester.StartDummyTest();
}
else if (choice == 3)
{
// 대화형 스트레스 테스트 설정
Log.Information("클라이언트 수 (기본 50): ");
string? countInput = Console.ReadLine();
CLIENT_COUNT = string.IsNullOrEmpty(countInput) ? 50 : int.Parse(countInput);
Log.Information("테스트 시간(초) (기본 60, 0=무제한): ");
string? durInput = Console.ReadLine();
int dur = string.IsNullOrEmpty(durInput) ? 60 : int.Parse(durInput);
await tester.StartStressTest(dur, 100, 1000, 10);
}
}
}

View File

@@ -0,0 +1,203 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using ClientTester.DummyService;
using ClientTester.Packet;
using LiteNetLib;
using LiteNetLib.Utils;
using Serilog;
namespace ClientTester.StressTest;
/// <summary>
/// 스트레스 테스트용 클라이언트.
/// Echo RTT 측정 + 이동 패킷 전송을 동시에 수행.
/// </summary>
public class StressTestClient
{
private NetManager manager;
private EventBasedNetListener listener;
private NetDataWriter? writer;
public NetPeer? peer;
public int clientId;
// 이동
private Vector3 position = new Vector3();
private int rotY;
private float moveSpeed = 3.5f;
private float distance;
private float preTime;
private readonly Stopwatch moveClock = Stopwatch.StartNew();
private float posX, posZ, dirX, dirZ;
public MapBounds Map { get; set; } = new MapBounds(-50f, 50f, -50f, 50f);
// RTT 측정
private readonly ConcurrentDictionary<int, long> pendingPings = new();
private int seqNumber;
private const int MAX_PENDING = 500;
/// <summary>개별 RTT 기록 (퍼센타일 계산용)</summary>
public ConcurrentBag<double> RttSamples { get; } = new();
// 통계
public int SentCount { get; set; }
public int ReceivedCount { get; set; }
public int RttCount { get; set; }
public double TotalRttMs { get; set; }
public double LastRttMs { get; set; }
public double AvgRttMs => RttCount > 0 ? TotalRttMs / RttCount : 0;
public bool IsConnected => peer != null;
public StressTestClient(int 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.Debug("[Stress {Id:000}] 연결됨", clientId);
DummyAccTokenPacket token = new DummyAccTokenPacket { Token = clientId };
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.DUMMY_ACC_TOKEN, token);
writer!.Put(data);
peer.Send(writer, DeliveryMethod.ReliableOrdered);
writer.Reset();
};
listener.NetworkReceiveEvent += (p, reader, ch, dm) =>
{
ReceivedCount++;
try
{
byte[] raw = reader.GetRemainingBytes();
if (raw.Length >= 4)
{
ushort type = BitConverter.ToUInt16(raw, 0);
ushort size = BitConverter.ToUInt16(raw, 2);
if (type == (ushort)PacketCode.ECHO && size > 0 && raw.Length >= 4 + size)
{
byte[] payload = new byte[size];
Array.Copy(raw, 4, payload, 0, size);
EchoPacket echo = PacketSerializer.DeserializePayload<EchoPacket>(payload);
if (echo.Str.StartsWith("Echo seq:") &&
int.TryParse(echo.Str.AsSpan("Echo seq:".Length), out int seq) &&
pendingPings.TryRemove(seq, out long sentTick))
{
double rttMs = (Stopwatch.GetTimestamp() - sentTick) * 1000.0 / Stopwatch.Frequency;
LastRttMs = rttMs;
TotalRttMs += rttMs;
RttCount++;
RttSamples.Add(rttMs);
}
}
}
}
catch
{
// 파싱 실패는 무시 (다른 패킷 타입)
}
};
listener.PeerDisconnectedEvent += (p, info) =>
{
Log.Debug("[Stress {Id:000}] 끊김: {Reason}", clientId, info.Reason);
peer = null;
};
manager.Start();
manager.Connect(ip, port, key);
}
public void UpdateAndSendTransform()
{
if (peer == null || writer == null)
{
return;
}
// 이동 업데이트
float now = (float)moveClock.Elapsed.TotalSeconds;
float delta = preTime > 0f ? now - preTime : 0.1f;
preTime = now;
if (distance <= 0f)
{
int wallRotY = Map.GetRotYAwayFromWall(posX, posZ);
rotY = wallRotY >= 0
? (wallRotY + Random.Shared.Next(-30, 31) + 360) % 360
: (rotY + Random.Shared.Next(-30, 31) + 360) % 360;
float rad = rotY * MathF.PI / 180f;
dirX = MathF.Sin(rad);
dirZ = MathF.Cos(rad);
distance = moveSpeed * (3f + (float)Random.Shared.NextDouble() * 9f);
}
float step = MathF.Min(moveSpeed * delta, distance);
float nextX = posX + dirX * step;
float nextZ = posZ + dirZ * step;
bool hitWall = Map.Clamp(ref nextX, ref nextZ);
posX = nextX;
posZ = nextZ;
distance = hitWall ? 0f : distance - step;
position.X = posX;
position.Z = posZ;
// 전송
TransformPlayerPacket pkt = new TransformPlayerPacket
{
PlayerId = clientId,
RotY = rotY,
Position = new Packet.Position { X = position.X, Y = -11.09f, Z = position.Z }
};
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.TRANSFORM_PLAYER, pkt);
writer.Put(data);
peer.Send(writer, DeliveryMethod.Unreliable);
SentCount++;
writer.Reset();
}
public void SendPing()
{
if (peer == null || writer == null)
{
return;
}
int seq = seqNumber++;
pendingPings[seq] = Stopwatch.GetTimestamp();
if (pendingPings.Count > MAX_PENDING)
{
int cutoff = seq - MAX_PENDING;
foreach (int k in pendingPings.Keys)
{
if (k < cutoff)
{
pendingPings.TryRemove(k, out _);
}
}
}
EchoPacket echo = new EchoPacket { Str = $"Echo seq:{seq}" };
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.ECHO, echo);
writer.Put(data);
peer.Send(writer, DeliveryMethod.ReliableUnordered);
SentCount++;
writer.Reset();
}
public void PollEvents()
{
manager.PollEvents();
}
public void Stop()
{
manager.Stop();
}
}

View File

@@ -0,0 +1,398 @@
using System.Diagnostics;
using System.Globalization;
using System.Text;
using LiteNetLib;
using Serilog;
namespace ClientTester.StressTest;
/// <summary>
/// 스트레스/부하 테스트 서비스.
///
/// 기능:
/// - 점진적 Ramp-up (N초 간격으로 클라이언트 추가)
/// - 테스트 지속시간 제한
/// - 실시간 처리량 (packets/sec) 측정
/// - 퍼센타일 레이턴시 (P50, P95, P99) 계산
/// - CSV 결과 내보내기
/// </summary>
public class StressTestService
{
private readonly string ip;
private readonly int port;
private readonly string key;
private readonly int totalClients;
private readonly int rampUpIntervalMs;
private readonly int clientsPerRamp;
private readonly int sendIntervalMs;
private readonly int durationSec;
private readonly List<StressTestClient> clients = new();
private readonly object clientsLock = new();
private readonly Stopwatch testClock = new();
// 실시간 처리량 추적
private int prevTotalSent;
private int prevTotalRecv;
private long prevStatsTick;
public event Action? OnTestCompleted;
/// <summary>
/// 스트레스 테스트 서비스 생성.
/// </summary>
/// <param name="totalClients">총 클라이언트 수</param>
/// <param name="ip">서버 IP</param>
/// <param name="port">서버 포트</param>
/// <param name="key">연결 키</param>
/// <param name="durationSec">테스트 지속 시간 (초). 0 = 무제한</param>
/// <param name="sendIntervalMs">패킷 전송 주기 (ms)</param>
/// <param name="rampUpIntervalMs">Ramp-up 간격 (ms). 0 = 모두 즉시 접속</param>
/// <param name="clientsPerRamp">Ramp-up 당 추가할 클라이언트 수</param>
public StressTestService(
int totalClients, string ip, int port, string key,
int durationSec = 60, int sendIntervalMs = 100,
int rampUpIntervalMs = 1000, int clientsPerRamp = 10)
{
this.totalClients = totalClients;
this.ip = ip;
this.port = port;
this.key = key;
this.durationSec = durationSec;
this.sendIntervalMs = sendIntervalMs;
this.rampUpIntervalMs = rampUpIntervalMs;
this.clientsPerRamp = clientsPerRamp;
}
public async Task RunAsync(CancellationToken ct)
{
Log.Information("╔═══════════════════════════════════════════════╗");
Log.Information("║ STRESS TEST 시작 ║");
Log.Information("╠═══════════════════════════════════════════════╣");
Log.Information("║ 서버 : {Ip}:{Port}", ip, port);
Log.Information("║ 클라이언트 : {Count}명", totalClients);
Log.Information("║ 지속시간 : {Dur}초", durationSec == 0 ? "무제한" : durationSec);
Log.Information("║ 전송주기 : {Int}ms", sendIntervalMs);
Log.Information("║ Ramp-up : {Per}명 / {Int}ms", clientsPerRamp, rampUpIntervalMs);
Log.Information("╚═══════════════════════════════════════════════╝");
testClock.Start();
prevStatsTick = Stopwatch.GetTimestamp();
using CancellationTokenSource durationCts = durationSec > 0
? new CancellationTokenSource(TimeSpan.FromSeconds(durationSec))
: new CancellationTokenSource();
using CancellationTokenSource linked = CancellationTokenSource.CreateLinkedTokenSource(ct, durationCts.Token);
await Task.WhenAll(
RampUpLoopAsync(linked.Token),
PollLoopAsync(linked.Token),
SendLoopAsync(linked.Token),
StatsLoopAsync(linked.Token)
);
testClock.Stop();
OnTestCompleted?.Invoke();
}
/// <summary>점진적으로 클라이언트 추가</summary>
private async Task RampUpLoopAsync(CancellationToken ct)
{
int created = 0;
while (created < totalClients && !ct.IsCancellationRequested)
{
int batch = Math.Min(clientsPerRamp, totalClients - created);
for (int i = 0; i < batch; i++)
{
int id = created + 1; // 1-based (더미 범위)
StressTestClient client = new StressTestClient(id, ip, port, key);
lock (clientsLock)
{
clients.Add(client);
}
created++;
}
Log.Information("[RAMP-UP] {Created}/{Total} 클라이언트 생성됨 ({Elapsed:F1}s)",
created, totalClients, testClock.Elapsed.TotalSeconds);
if (created < totalClients && rampUpIntervalMs > 0)
{
await Task.Delay(rampUpIntervalMs, ct).ConfigureAwait(false);
}
}
Log.Information("[RAMP-UP] 완료 - 총 {Count}명 접속", created);
}
private async Task PollLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
List<StressTestClient> snapshot;
lock (clientsLock)
{
snapshot = new List<StressTestClient>(clients);
}
foreach (StressTestClient c in snapshot)
{
try
{
c.PollEvents();
}
catch
{
/* 무시 */
}
}
await Task.Delay(10, ct).ConfigureAwait(false);
}
}
private async Task SendLoopAsync(CancellationToken ct)
{
await Task.Delay(500, ct).ConfigureAwait(false);
while (!ct.IsCancellationRequested)
{
List<StressTestClient> snapshot;
lock (clientsLock)
{
snapshot = new List<StressTestClient>(clients);
}
foreach (StressTestClient c in snapshot)
{
c.UpdateAndSendTransform();
c.SendPing();
}
await Task.Delay(sendIntervalMs, ct).ConfigureAwait(false);
}
}
/// <summary>10초마다 실시간 통계 출력</summary>
private async Task StatsLoopAsync(CancellationToken ct)
{
await Task.Delay(5000, ct).ConfigureAwait(false);
while (!ct.IsCancellationRequested)
{
PrintLiveStats();
await Task.Delay(10000, ct).ConfigureAwait(false);
}
}
private void PrintLiveStats()
{
List<StressTestClient> snapshot;
lock (clientsLock)
{
snapshot = new List<StressTestClient>(clients);
}
int totalSent = snapshot.Sum(c => c.SentCount);
int totalRecv = snapshot.Sum(c => c.ReceivedCount);
int connected = snapshot.Count(c => c.IsConnected);
long now = Stopwatch.GetTimestamp();
double elapsedSec = (now - prevStatsTick) * 1.0 / Stopwatch.Frequency;
double sendRate = elapsedSec > 0 ? (totalSent - prevTotalSent) / elapsedSec : 0;
double recvRate = elapsedSec > 0 ? (totalRecv - prevTotalRecv) / elapsedSec : 0;
prevTotalSent = totalSent;
prevTotalRecv = totalRecv;
prevStatsTick = now;
double avgRtt = 0;
int rttClients = 0;
foreach (StressTestClient c in snapshot)
{
if (c.RttCount > 0)
{
avgRtt += c.AvgRttMs;
rttClients++;
}
}
if (rttClients > 0)
{
avgRtt /= rttClients;
}
Log.Information(
"[LIVE {Elapsed:F0}s] 접속={Conn}/{Total} | 전송={SendRate:F0}/s 수신={RecvRate:F0}/s | AvgRTT={Rtt:F2}ms",
testClock.Elapsed.TotalSeconds, connected, clients.Count, sendRate, recvRate, avgRtt);
}
/// <summary>최종 결과 리포트 출력</summary>
public void PrintFinalReport()
{
List<StressTestClient> snapshot;
lock (clientsLock)
{
snapshot = new List<StressTestClient>(clients);
}
int totalSent = 0, totalRecv = 0, connected = 0;
List<double> allRtt = new();
foreach (StressTestClient c in snapshot)
{
totalSent += c.SentCount;
totalRecv += c.ReceivedCount;
if (c.IsConnected)
{
connected++;
}
foreach (double r in c.RttSamples)
{
allRtt.Add(r);
}
}
allRtt.Sort();
double p50 = Percentile(allRtt, 0.50);
double p95 = Percentile(allRtt, 0.95);
double p99 = Percentile(allRtt, 0.99);
double avg = allRtt.Count > 0 ? allRtt.Average() : 0;
double min = allRtt.Count > 0 ? allRtt[0] : 0;
double max = allRtt.Count > 0 ? allRtt[^1] : 0;
double durSec = testClock.Elapsed.TotalSeconds;
double throughput = durSec > 0 ? totalSent / durSec : 0;
Log.Information("");
Log.Information("╔═══════════════════════════════════════════════╗");
Log.Information("║ STRESS TEST 최종 리포트 ║");
Log.Information("╠═══════════════════════════════════════════════╣");
Log.Information("║ 테스트 시간 : {Dur:F1}초", durSec);
Log.Information("║ 클라이언트 : {Conn}/{Total} 접속 유지", connected, snapshot.Count);
Log.Information("╠═══════════════════════════════════════════════╣");
Log.Information("║ [처리량]");
Log.Information("║ 총 전송 : {Sent:N0} 패킷", totalSent);
Log.Information("║ 총 수신 : {Recv:N0} 패킷", totalRecv);
Log.Information("║ 처리량 : {Thr:F1} 패킷/초", throughput);
Log.Information("╠═══════════════════════════════════════════════╣");
Log.Information("║ [레이턴시] (RTT 샘플: {Count:N0}개)", allRtt.Count);
Log.Information("║ Min : {Min:F2} ms", min);
Log.Information("║ Avg : {Avg:F2} ms", avg);
Log.Information("║ P50 : {P50:F2} ms", p50);
Log.Information("║ P95 : {P95:F2} ms", p95);
Log.Information("║ P99 : {P99:F2} ms", p99);
Log.Information("║ Max : {Max:F2} ms", max);
Log.Information("╠═══════════════════════════════════════════════╣");
// 클라이언트별 요약 (상위 5명 최악 RTT)
List<StressTestClient> worstClients = snapshot
.Where(c => c.RttCount > 0)
.OrderByDescending(c => c.AvgRttMs)
.Take(5)
.ToList();
if (worstClients.Count > 0)
{
Log.Information("║ [최악 RTT 상위 5 클라이언트]");
foreach (StressTestClient c in worstClients)
{
NetStatistics? stats = c.peer?.Statistics;
float lossPct = stats?.PacketLossPercent ?? 0f;
Log.Information("║ Client {Id:000}: AvgRTT={Rtt:F2}ms Loss={Loss:F1}% Sent={S} Recv={R}",
c.clientId, c.AvgRttMs, lossPct, c.SentCount, c.ReceivedCount);
}
}
Log.Information("╚═══════════════════════════════════════════════╝");
}
/// <summary>결과를 CSV 파일로 내보내기</summary>
public void ExportCsv(string path)
{
List<StressTestClient> snapshot;
lock (clientsLock)
{
snapshot = new List<StressTestClient>(clients);
}
StringBuilder sb = new();
sb.AppendLine("ClientId,Sent,Received,AvgRttMs,RttCount,PacketLoss,PacketLossPct,Connected");
foreach (StressTestClient c in snapshot)
{
NetStatistics? stats = c.peer?.Statistics;
long loss = stats?.PacketLoss ?? 0;
float lossPct = stats?.PacketLossPercent ?? 0f;
sb.AppendLine(string.Format(CultureInfo.InvariantCulture,
"{0},{1},{2},{3:F3},{4},{5},{6:F1},{7}",
c.clientId, c.SentCount, c.ReceivedCount,
c.AvgRttMs, c.RttCount, loss, lossPct, c.IsConnected));
}
// 요약 행
List<double> allRtt = new();
foreach (StressTestClient c in snapshot)
foreach (double r in c.RttSamples)
{
allRtt.Add(r);
}
allRtt.Sort();
sb.AppendLine();
sb.AppendLine("# Summary");
sb.AppendLine(string.Format(CultureInfo.InvariantCulture,
"# Duration={0:F1}s,Clients={1},TotalSent={2},TotalRecv={3}",
testClock.Elapsed.TotalSeconds, snapshot.Count,
snapshot.Sum(c => c.SentCount), snapshot.Sum(c => c.ReceivedCount)));
sb.AppendLine(string.Format(CultureInfo.InvariantCulture,
"# P50={0:F2}ms,P95={1:F2}ms,P99={2:F2}ms",
Percentile(allRtt, 0.50), Percentile(allRtt, 0.95), Percentile(allRtt, 0.99)));
File.WriteAllText(path, sb.ToString());
Log.Information("[CSV] 결과 저장: {Path}", path);
}
public void Stop()
{
List<StressTestClient> snapshot;
lock (clientsLock)
{
snapshot = new List<StressTestClient>(clients);
}
foreach (StressTestClient c in snapshot)
{
c.Stop();
}
Log.Information("[STRESS] 모든 클라이언트 종료됨.");
}
private static double Percentile(List<double> sorted, double p)
{
if (sorted.Count == 0)
{
return 0;
}
double index = p * (sorted.Count - 1);
int lower = (int)Math.Floor(index);
int upper = (int)Math.Ceiling(index);
if (lower == upper)
{
return sorted[lower];
}
double frac = index - lower;
return sorted[lower] * (1 - frac) + sorted[upper] * frac;
}
}

View File

@@ -0,0 +1,196 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Serilog;
namespace ClientTester.Utils;
/// <summary>
/// 릴리즈 빌드 크래시 덤프 핸들러
///
/// Register() 를 Program.cs 최상단에서 한 번 호출.
///
/// 생성 파일 (crashes/ 폴더):
/// Debug : crash_YYYY-MM-DD_HH-mm-ss.log
/// Release : crash_YYYY-MM-DD_HH-mm-ss.log
/// crash_YYYY-MM-DD_HH-mm-ss.dmp ← 메모리 덤프 추가
/// </summary>
public static class CrashDumpHandler
{
private const string CRASH_DIR = "crashes";
private static int registered = 0;
public static void Register()
{
// 중복 등록 방지
if (Interlocked.Exchange(ref registered, 1) != 0)
{
return;
}
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
Log.Information("[CrashDump] 핸들러 등록 완료 (CrashDir={Dir})", Path.GetFullPath(CRASH_DIR));
}
// ─── 핸들러 ──────────────────────────────────────────────────────────
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception? ex = e.ExceptionObject as Exception;
bool isTerminating = e.IsTerminating;
string tag = $"[CrashDump] UnhandledException (IsTerminating={isTerminating})";
WriteCrash(tag, ex);
}
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
{
e.SetObserved(); // 프로세스 종료 방지
string tag = "[CrashDump] UnobservedTaskException";
WriteCrash(tag, e.Exception);
}
// ─── 핵심 처리 ───────────────────────────────────────────────────────
private static void WriteCrash(string tag, Exception? ex)
{
try
{
Directory.CreateDirectory(CRASH_DIR);
string timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
string basePath = Path.Combine(CRASH_DIR, $"crash_{timestamp}");
// 1. 크래시 로그 작성
string logPath = $"{basePath}.log";
WriteCrashLog(logPath, ex);
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)
{
// 덤프 저장 실패는 무시 (이미 크래시 중이므로)
Log.Error(writeEx, "[CrashDump] 덤프 저장 실패");
}
finally
{
Log.CloseAndFlush();
}
}
private static void WriteCrashLog(string path, Exception? ex)
{
StringBuilder sb = new();
sb.AppendLine("═══════════════════════════════════════════════════");
sb.AppendLine($" CRASH REPORT {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
sb.AppendLine("═══════════════════════════════════════════════════");
sb.AppendLine();
// 환경 정보
sb.AppendLine("[Environment]");
sb.AppendLine($" OS : {RuntimeInformation.OSDescription}");
sb.AppendLine($" Runtime : {RuntimeInformation.FrameworkDescription}");
sb.AppendLine($" PID : {Environment.ProcessId}");
sb.AppendLine($" WorkDir : {Environment.CurrentDirectory}");
sb.AppendLine($" MachineName: {Environment.MachineName}");
sb.AppendLine();
// 스레드 정보
sb.AppendLine("[Thread]");
sb.AppendLine($" ThreadId : {Environment.CurrentManagedThreadId}");
sb.AppendLine();
// 예외 정보
sb.AppendLine("[Exception]");
if (ex is null)
{
sb.AppendLine(" (예외 객체 없음)");
}
else
{
AppendException(sb, ex, depth: 0);
}
File.WriteAllText(path, sb.ToString(), Encoding.UTF8);
}
private static void AppendException(StringBuilder sb, Exception ex, int depth)
{
string indent = new string(' ', depth * 2);
sb.AppendLine($"{indent} Type : {ex.GetType().FullName}");
sb.AppendLine($"{indent} Message : {ex.Message}");
sb.AppendLine($"{indent} Source : {ex.Source}");
sb.AppendLine();
sb.AppendLine($"{indent} StackTrace:");
if (ex.StackTrace is not null)
{
foreach (string line in ex.StackTrace.Split('\n'))
{
sb.AppendLine($"{indent} {line.TrimEnd()}");
}
}
if (ex is AggregateException agg)
{
foreach (Exception inner in agg.InnerExceptions)
{
sb.AppendLine();
sb.AppendLine($"{indent} [InnerException]");
AppendException(sb, inner, depth + 1);
}
}
else if (ex.InnerException is not null)
{
sb.AppendLine();
sb.AppendLine($"{indent} [InnerException]");
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

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

View File

@@ -0,0 +1,6 @@
{
"ServerIp": "j14a301.p.ssafy.io",
"ServerPort": 40001,
"ConnectionKey": "test",
"ClientCount": 80
}

304
ClientTester/README.md Normal file
View File

@@ -0,0 +1,304 @@
# ClientTester - MMO 서버 테스트 도구
MMO Game Server의 네트워크 성능 검증 및 부하 테스트를 위한 클라이언트 시뮬레이터.
---
## 1. 환경 (라이브러리)
| 항목 | 버전 | 용도 |
|------|------|------|
| .NET | 9.0 | 런타임 |
| LiteNetLib | 2.0.2 | UDP 네트워크 통신 (서버와 동일) |
| protobuf-net | 3.2.56 | 패킷 직렬화/역직렬화 |
| Serilog | 4.3.1 | 구조적 로깅 |
| Serilog.Sinks.Console | 6.0.0 | 콘솔 출력 |
| Serilog.Sinks.File | 7.0.0 | 파일 로깅 |
| Microsoft.Diagnostics.NETCore.Client | 0.2.553101 | 크래시 힙 덤프 (Release만) |
### 빌드
```bash
cd ClientTester/EchoClientTester
dotnet build
```
---
## 2. 디렉토리 구조
```
ClientTester/
├── EchoClientTester/
│ ├── Program.cs # 진입점 (대화형 + CLI)
│ ├── EchoClientTester.csproj
│ ├── Vector3.cs # 위치 구조체
│ │
│ ├── DummyService/ # 이동 테스트
│ │ ├── DummyClientService.cs # 다중 더미 클라 관리
│ │ ├── DummyClients.cs # 개별 더미 클라 (이동 시뮬)
│ │ └── MapBounds.cs # 맵 경계 / 벽 충돌
│ │
│ ├── EchoDummyService/ # Echo RTT 테스트
│ │ ├── EchoDummyClientService.cs # 다중 에코 클라 관리
│ │ └── EchoDummyClients.cs # 개별 에코 클라 (RTT 측정)
│ │
│ ├── StressTest/ # 부하/스트레스 테스트
│ │ ├── StressTestService.cs # 오케스트레이터 (Ramp-up, 통계, CSV)
│ │ └── StressTestClient.cs # 통합 클라 (이동 + Echo 동시)
│ │
│ ├── Packet/ # 패킷 정의 (서버와 동일 프로토콜)
│ │ ├── PacketHeader.cs # PacketCode Enum
│ │ ├── PacketBody.cs # Protobuf 패킷 클래스
│ │ └── PacketSerializer.cs # 직렬화 유틸
│ │
│ └── Utils/
│ └── CrashDumpHandler.cs # 크래시 로그 + 힙 덤프
└── TempServer/ # 간이 에코 서버 (독립 테스트용)
└── Program.cs
```
---
## 3. 사용방법
### 3.1 대화형 모드
```bash
dotnet run
```
```
========== 더미 클라 테스터 ==========
1. 에코 서버
2. 더미 클라(이동만)
3. 스트레스 테스트 (부하)
====================================
1 / 2 / 3 :
```
| 모드 | 설명 |
|------|------|
| 1. 에코 서버 | Echo 패킷 송수신, RTT(Round-Trip Time) 측정 |
| 2. 더미 클라 | 이동(Transform) 패킷 전송, 패킷 손실률 측정 |
| 3. 스트레스 테스트 | Ramp-up + 이동 + Echo 동시, 퍼센타일 레이턴시, CSV 내보내기 |
### 3.2 CLI 모드 (스트레스 테스트)
```bash
# 기본 실행 (50명, 60초)
dotnet run -- stress
# 100명 클라이언트, 120초 테스트
dotnet run -- stress -c 100 -d 120
# 원격 서버 대상, 커스텀 설정
dotnet run -- stress -c 200 -d 60 -r 500 -b 20 --ip 192.168.0.10 --port 9500
# 도움말
dotnet run -- --help
```
#### CLI 옵션
| 옵션 | 축약 | 기본값 | 설명 |
|------|------|--------|------|
| `--clients` | `-c` | 50 | 총 클라이언트 수 |
| `--duration` | `-d` | 60 | 테스트 지속 시간 (초, 0=무제한) |
| `--interval` | `-i` | 100 | 패킷 전송 주기 (ms) |
| `--ramp` | `-r` | 1000 | Ramp-up 간격 (ms) |
| `--batch` | `-b` | 10 | Ramp-up 당 추가 클라이언트 수 |
| `--ip` | | localhost | 서버 IP 주소 |
| `--port` | | 9500 | 서버 포트 |
### 3.3 출력 파일
| 경로 | 내용 |
|------|------|
| `logs2/log_{timestamp}.txt` | 전체 실행 로그 |
| `results/stress_{N}clients_{timestamp}.csv` | 스트레스 테스트 결과 (클라이언트별 통계) |
| `crashes/crash_{timestamp}.log` | 크래시 스택 트레이스 |
| `crashes/crash_{timestamp}.dmp` | 힙 덤프 (Release 빌드만) |
---
## 4. 파이프라인
### 4.1 에코 테스트 (모드 1)
```
[클라이언트 N개 동시 생성]
[연결] UDP Connect → ServerBase.OnConnectionRequest()
[PollLoop] 10ms 주기로 네트워크 이벤트 처리
[SendLoop] 100ms 주기로 Echo 패킷 전송
[송신] EchoPacket { Str = "Echo seq:{N}" }
→ PacketSerializer.Serialize()
→ 4바이트 헤더(type + size) + Protobuf 페이로드
→ DeliveryMethod.ReliableUnordered
[수신] 서버가 Echo 패킷 그대로 반환
→ seq 번호로 pendingPings 조회
→ RTT 계산: (수신시각 - 송신시각) / Stopwatch.Frequency
[통계] 클라이언트별: AvgRTT, LastRTT, Sent, Recv, PacketLoss%
전체: 총 Sent/Recv, 평균 RTT
```
### 4.2 이동 테스트 (모드 2)
```
[클라이언트 N개 동시 생성]
[연결 + 인증]
DummyAccTokenPacket { Token = clientId }
→ DeliveryMethod.ReliableOrdered
[이동 시뮬레이션 - UpdateDummy()]
┌────────────────────────────────────────┐
│ 1. 델타 타임 계산 (Stopwatch) │
│ 2. 남은 거리 = 0 이면: │
│ - 벽 근처? → 반대 방향 회전 │
│ - 아니면 → 현재 방향 ±30도 랜덤 회전 │
│ - 목표 거리 = moveSpeed × (3~12초) │
│ 3. 이번 틱 이동 (moveSpeed × delta) │
│ 4. MapBounds.Clamp() → 벽 충돌 처리 │
└────────────────────────────────────────┘
[송신] TransformPlayerPacket { PlayerId, Position(X,0,Z), RotY }
→ DeliveryMethod.Unreliable (손실 감수)
[통계] 클라이언트별: Sent, Recv, PacketLoss%
```
### 4.3 스트레스 테스트 (모드 3 / CLI)
```
[설정 입력] CLI 인자 또는 대화형 입력
[Ramp-up Loop]
┌────────────────────────────────────┐
│ rampInterval(1000ms)마다 │
│ clientsPerRamp(10)명씩 클라이언트 생성 │
│ → totalClients 도달 시 중단 │
└────────────────────────────────────┘
↓ (병렬 실행)
[PollLoop] 10ms 주기 네트워크 이벤트
[SendLoop] sendInterval(100ms) 주기
├─ UpdateAndSendTransform() (이동 - Unreliable)
└─ SendPing() (Echo - ReliableUnordered)
[StatsLoop] 10초마다 실시간 통계 출력
[지속시간 만료 또는 Ctrl+C]
[최종 리포트]
├─ 처리량: 총 Sent/Recv, 패킷/초
├─ 레이턴시: Min, Avg, P50, P95, P99, Max
├─ 최악 RTT 상위 5 클라이언트 상세
└─ CSV 파일 자동 저장
```
### 4.4 패킷 직렬화 파이프라인
```
객체 (e.g. TransformPlayerPacket)
protobuf-net Serialize → byte[] payload
PacketSerializer.Serialize()
┌──────────────────────────────┐
│ [2B type] [2B size] [payload] │
│ ushort ushort byte[] │
└──────────────────────────────┘
NetDataWriter.Put(data)
peer.Send(writer, DeliveryMethod)
```
---
## 5. 테스트 모드별 기능 비교
| 기능 | 에코 (1) | 이동 (2) | 스트레스 (3) |
|------|:--------:|:--------:|:------------:|
| 동시접속 클라이언트 | 10 (고정) | 10 (고정) | N (설정 가능) |
| 인증 패킷 전송 | X | O | O |
| 이동 시뮬레이션 | X | O | O |
| Echo RTT 측정 | O | X | O |
| 패킷 손실 추적 | O | O | O |
| 점진적 Ramp-up | X | X | O |
| 지속시간 제한 | 무제한 | 무제한 | 설정 가능 |
| 실시간 통계 | X | X | O (10초 주기) |
| 퍼센타일 레이턴시 | X (평균만) | X | O (P50/P95/P99) |
| CSV 내보내기 | X | X | O |
| CLI 인자 | X | X | O |
| 최악 클라이언트 분석 | X | X | O (상위 5) |
---
## 6. 구현 진행도
### 완료
| 항목 | 상태 | 설명 |
|------|:----:|------|
| Echo RTT 측정 | **완료** | seq 기반 ping/pong, Stopwatch 고정밀 타이머 |
| 더미 이동 시뮬레이션 | **완료** | 벽 충돌, 랜덤 방향 전환, 델타 타임 기반 이동 |
| 맵 경계 처리 | **완료** | MapBounds (Clamp, 벽 반대 방향 계산) |
| 패킷 손실 추적 | **완료** | LiteNetLib.NetStatistics 활용 |
| 크래시 덤프 | **완료** | Debug: .log / Release: .log + .dmp |
| 로깅 (콘솔+파일) | **완료** | Serilog 타임스탬프별 로그 파일 |
| Graceful Shutdown | **완료** | Ctrl+C → CancellationToken → 통계 출력 후 종료 |
| 스트레스 테스트 | **완료** | Ramp-up, 퍼센타일, CSV, CLI 인자 |
| CLI 인자 지원 | **완료** | `stress -c N -d T --ip --port` |
### 미구현 / 향후 작업
| 항목 | 상태 | 설명 |
|------|:----:|------|
| 채널 입장 시뮬레이션 | 미구현 | INTO_CHANNEL 패킷 전송 후 게임 루프 진입 |
| 전투 액션 시뮬레이션 | 미구현 | ACTION_PLAYER (공격/스킬) 패킷 전송 |
| 상태 변경 시뮬레이션 | 미구현 | STATE_PLAYER (HP/MP) 패킷 전송 |
| JWT 토큰 인증 테스트 | 미구현 | ACC_TOKEN 방식 인증 플로우 검증 |
| 서버 응답 검증 | 미구현 | 수신 패킷 내용 파싱 및 정합성 체크 |
| 테스트 시나리오 스크립트 | 미구현 | JSON/YAML 기반 테스트 시나리오 정의 |
| 그래프 출력 | 미구현 | RTT/처리량 시계열 차트 생성 |
---
## 7. 설정 참고
### 서버 연결 기본값
| 항목 | 값 |
|------|-----|
| IP | `localhost` |
| Port | `9500` |
| Connection Key | `test` |
### 이동 시뮬레이션 파라미터
| 항목 | 값 | 설명 |
|------|-----|------|
| moveSpeed | 3.5 | 이동 속도 (units/sec) |
| 맵 범위 | -50 ~ 50 (X, Z) | 100x100 영역 |
| 벽 감지 마진 | 0.5 | 벽 근처 판정 거리 |
| 목표 거리 | moveSpeed x 3~12초 | 직진 후 방향 전환 |
| 방향 전환 | 현재 ±30도 랜덤 | 벽 근처 시 반대 방향 강제 |
### 스트레스 테스트 기본값
| 항목 | 값 | 설명 |
|------|-----|------|
| 클라이언트 수 | 50 | `-c` 옵션 |
| 지속 시간 | 60초 | `-d` 옵션 |
| 전송 주기 | 100ms | `-i` 옵션 |
| Ramp-up 간격 | 1000ms | `-r` 옵션 |
| Ramp-up 배치 | 10명 | `-b` 옵션 |
| 실시간 통계 주기 | 10초 | 고정 |
| Echo 최대 pending | 500 | 메모리 누수 방지 |

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

@@ -0,0 +1,356 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using MMOserver.Config;
using MMOserver.Utils;
using Serilog;
namespace MMOserver.Api;
public class RestApi : Singleton<RestApi>
{
private const int MAX_RETRY = 3;
private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(1);
private readonly HttpClient httpClient = new() { Timeout = TimeSpan.FromSeconds(5) };
public RestApi()
{
httpClient.DefaultRequestHeaders.Add("X-API-Key", AppConfig.RestApi.ApiKey);
}
// 토큰 검증 - 성공 시 username 반환
// 401 → 재시도 없이 즉시 null 반환 (토큰 자체가 무효)
// 타임아웃/네트워크 오류 → 최대 MAX_RETRY회 재시도 후 null 반환
public async Task<string?> VerifyTokenAsync(string token)
{
string url = AppConfig.RestApi.BaseUrl + AppConfig.RestApi.VerifyToken;
for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
{
try
{
HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, new { token });
// 401: 토큰 자체가 무효 → 재시도해도 같은 결과, 즉시 반환
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Log.Warning("[RestApi] 토큰 인증 실패 (401)");
return null;
}
response.EnsureSuccessStatusCode();
AuthVerifyResponse? result = await response.Content.ReadFromJsonAsync<AuthVerifyResponse>();
return result?.Username;
}
catch (Exception ex) when (attempt < MAX_RETRY)
{
// 일시적 장애 (타임아웃, 네트워크 오류 등) → 재시도
Log.Warning("[RestApi] 통신 실패 (시도 {Attempt}/{Max}): {Message}", attempt, MAX_RETRY, ex.Message);
await Task.Delay(RETRY_DELAY);
}
catch (Exception ex)
{
// 마지막 시도까지 실패
Log.Error("[RestApi] 최종 통신 실패 ({Max}회 시도): {Message}", MAX_RETRY, ex.Message);
}
}
return null;
}
// 플레이어 프로필 조회 - 성공 시 PlayerProfileResponse 반환
public async Task<PlayerProfileResponse?> GetPlayerProfileAsync(string username)
{
string url = AppConfig.RestApi.BaseUrl + "/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;
}
// 레이드 채널 접속 여부 체크
// 성공 시 BossRaidResult 반환, 실패/거절 시 null 반환
public async Task<BossRaidResult?> BossRaidAccessAsync(List<string> userNames, int bossId)
{
string url = AppConfig.RestApi.BaseUrl + AppConfig.RestApi.BossRaidAccess;
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: 이미 레이드 중 / 503: 이용 가능한 방 없음
if (response.StatusCode == HttpStatusCode.BadRequest ||
response.StatusCode == HttpStatusCode.Conflict ||
response.StatusCode == HttpStatusCode.ServiceUnavailable)
{
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;
}
// 게임 데이터 저장 (채널 퇴장 시 위치/플레이타임 저장)
public async Task<bool> SaveGameDataAsync(string username, float? posX, float? posY, float? posZ, float? rotY, long? playTimeDelta)
{
string url = AppConfig.RestApi.BaseUrl + "/api/internal/player/save?username=" + Uri.EscapeDataString(username);
Dictionary<string, object?> body = new();
if (posX.HasValue)
{
body["lastPosX"] = posX.Value;
}
if (posY.HasValue)
{
body["lastPosY"] = posY.Value;
}
if (posZ.HasValue)
{
body["lastPosZ"] = posZ.Value;
}
if (rotY.HasValue)
{
body["lastRotY"] = rotY.Value;
}
if (playTimeDelta.HasValue)
{
body["playTimeDelta"] = playTimeDelta.Value;
}
for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
{
try
{
HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, body);
response.EnsureSuccessStatusCode();
return true;
}
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 false;
}
private sealed class AuthVerifyResponse
{
[JsonPropertyName("username")]
public string? Username
{
get;
set;
}
}
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;
}
[JsonPropertyName("lastPosX")]
public double LastPosX
{
get;
set;
}
[JsonPropertyName("lastPosY")]
public double LastPosY
{
get;
set;
}
[JsonPropertyName("lastPosZ")]
public double LastPosZ
{
get;
set;
}
[JsonPropertyName("lastRotY")]
public double LastRotY
{
get;
set;
}
}
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;
} = new();
}
}

View File

@@ -0,0 +1,74 @@
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 int ChannelCount
{
get;
}
public ServerConfig(IConfigurationSection section)
{
Port = int.Parse(section["Port"] ?? throw new InvalidOperationException("Server:Port is required in config.json"));
ChannelCount = int.Parse(section["ChannelCount"] ?? "1");
}
}
public sealed class RestApiConfig
{
public string BaseUrl
{
get;
}
public string VerifyToken
{
get;
}
public string BossRaidAccess
{
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");
BossRaidAccess = section["BossRaidAccess"] ?? 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
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
# ServerLib 의존성 포함해서 restore (캐시 레이어 최적화)
COPY ["MMOserver/MMOserver.csproj", "MMOserver/"]
COPY ["ServerLib/ServerLib.csproj", "ServerLib/"]
RUN dotnet restore "MMOserver/MMOserver.csproj"
COPY . .
WORKDIR "/src/MMOserver"

View File

@@ -1,19 +1,59 @@
using LiteNetLib;
using MMOserver.Game.Channel.Maps;
using MMOserver.Game.Channel.Maps.InstanceDungeun;
using MMOserver.Game.Party;
namespace MMOserver.Game.Channel;
/*
* Channel 클래스
* - 채널 내 Peer 관리
* - 채널 내 유저관리
* - 맵 관리
* - 인스턴스 던전 관리
* - 동적 맵 id 생성
*/
public class Channel
{
// 로비
private Robby robby = new Robby();
// 채널 내 유저 NetPeer (hashKey → NetPeer) — BroadcastToChannel 교차 조회 제거용
private readonly Dictionary<int, NetPeer> connectPeers = new();
// 채널 내 유저 상태 (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
{
get;
private set;
}
public int UserCount
@@ -28,25 +68,60 @@ public class Channel
private set;
} = 100;
public Channel(int channelId)
{
ChannelId = channelId;
}
public void AddUser(long userId, Player player)
public void AddUser(int userId, Player player, NetPeer peer)
{
connectUsers[userId] = player;
connectPeers[userId] = peer;
UserCount++;
// 처음 접속 시 1번 맵(로비)으로 입장
ChangeMap(userId, player, 1);
}
public void RemoveUser(long userId)
public void RemoveUser(int userId)
{
// 현재 맵에서도 제거
if (connectUsers.TryGetValue(userId, out Player? player) &&
maps.TryGetValue(player.CurrentMapId, out AMap? currentMap))
{
currentMap.RemoveUser(userId);
}
if (connectUsers.Remove(userId))
{
connectUsers.Remove(userId);
UserCount--;
}
// 채널 내 모든 유저의 hashKey 반환
public IEnumerable<long> GetConnectUsers()
connectPeers.Remove(userId);
}
// 맵 이동 (현재 맵 제거 → 새 맵 추가 → CurrentMapId 갱신)
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;
}
@@ -57,14 +132,27 @@ public class Channel
return connectUsers.Values;
}
// 채널 내 모든 NetPeer 반환 — BroadcastToChannel 전용 (sessions 교차 조회 불필요)
public IEnumerable<NetPeer> GetConnectPeers()
{
return connectPeers.Values;
}
// 특정 유저의 Player 반환
public Player? GetPlayer(long userId)
public Player? GetPlayer(int userId)
{
connectUsers.TryGetValue(userId, out Player? player);
return player;
}
public int HasUser(long userId)
// 특정 유저의 NetPeer 반환
public NetPeer? GetPeer(int userId)
{
connectPeers.TryGetValue(userId, out NetPeer? peer);
return peer;
}
public int HasUser(int userId)
{
if (connectUsers.ContainsKey(userId))
{
@@ -74,9 +162,61 @@ public class Channel
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,29 +1,27 @@
namespace MMOserver.Game.Channel;
using LiteNetLib;
using MMOserver.Config;
using MMOserver.Utils;
public class ChannelManager
{
// 일단은 채널은 서버 켤때 고정으로간다 1개
public static ChannelManager Instance
{
get;
} = new ChannelManager();
namespace MMOserver.Game.Channel;
public class ChannelManager : Singleton<ChannelManager>
{
// 채널 관리
private List<Channel> channels = new List<Channel>();
private Dictionary<int, Channel> channels = new Dictionary<int, Channel>();
// 채널별 유저 관리 (유저 key, 채널 val)
private Dictionary<long, int> connectUsers = new Dictionary<long, int>();
private Dictionary<int, int> connectUsers = new Dictionary<int, int>();
public ChannelManager()
{
Initializer();
Initializer(AppConfig.Server.ChannelCount);
}
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));
}
}
@@ -32,23 +30,26 @@ public class ChannelManager
return channels[channelId];
}
public List<Channel> GetChannels()
public Dictionary<int, Channel> GetChannels()
{
return channels;
}
public void AddUser(int channelId, long userId, Player player)
public void AddUser(int channelId, int userId, Player player, NetPeer peer)
{
// 유저 추가
// 유저 추가 (채널 이동 시 기존 매핑 덮어쓰기 허용)
connectUsers[userId] = channelId;
// 채널에 유저 추가
channels[channelId].AddUser(userId, player);
// 채널에 유저 + peer 추가
channels[channelId].AddUser(userId, player, peer);
}
public bool RemoveUser(long userId)
public bool RemoveUser(int userId)
{
// 채널 있으면
int channelId = connectUsers[userId];
// 채널에 없는 유저면 스킵
if (!connectUsers.TryGetValue(userId, out int channelId))
{
return false;
}
// 날린다.
if (channelId >= 0)
@@ -61,7 +62,7 @@ public class ChannelManager
return false;
}
public int HasUser(long userId)
public int HasUser(int userId)
{
int channelId = -1;
if (connectUsers.ContainsKey(userId))
@@ -77,7 +78,7 @@ public class ChannelManager
return channelId;
}
public Dictionary<long, int> GetConnectUsers()
public Dictionary<int, int> GetConnectUsers()
{
return connectUsers;
}

View File

@@ -0,0 +1,29 @@
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,15 @@
namespace MMOserver.Game.Channel.Maps;
/*
* 맵 타입
* - ROBBY : 마을
* - DUNGEON : 오픈월드 던전 (마을 외곽)
* - INSTANCE : 인스턴스 레이드 던전(포톤용)
*/
public enum EnumMap : int
{
NONE = 0,
ROBBY = 1,
DUNGEON = 2,
INSTANCE = 10,
}

View File

@@ -0,0 +1,36 @@
using MMOserver.Game.Channel.Maps;
using MMOserver.Game.Engine;
namespace MMOserver.Game.Channel.Maps.InstanceDungeun;
/*
* 인스턴스 보스 레이드에 진입은 하나의 Map으로 처리
*/
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,16 +2,27 @@
namespace MMOserver.Game.Channel.Maps;
public class Robby
/*
* 마을(로비)
*/
public class Robby : AMap
{
// 마을 시작 지점 넣어 둔다.
public static Vector3 StartPosition
{
get;
set;
} = new Vector3(0, 0, 0);
private EnumMap enumMap;
private int mapId;
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;
}
}

View File

@@ -1,303 +0,0 @@
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)
{
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)
{
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)
{
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,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

@@ -1,8 +1,10 @@
using MMOserver.Packet;
namespace MMOserver.Game;
public class Player
{
public long HashKey
public int HashKey
{
get;
set;
@@ -50,6 +52,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
{
@@ -74,4 +106,39 @@ public class Player
get;
set;
}
// 현재 위치한 맵 ID
public int CurrentMapId
{
get;
set;
}
// 레이드 입장 전 이전 맵 ID (레이드 종료 후 복귀용, 서버 캐싱)
public int PreviousMapId
{
get;
set;
}
public PlayerInfo ToPlayerInfo()
{
return new PlayerInfo
{
PlayerId = this.PlayerId,
Nickname = this.Nickname,
Level = this.Level,
Hp = this.Hp,
MaxHp = this.MaxHp,
Mp = this.Mp,
MaxMp = this.MaxMp,
Position = new Position { X = this.PosX, Y = this.PosY, Z = this.PosZ },
RotY = this.RotY,
Experience = this.Experience,
NextExp = this.NextExp,
AttackPower = this.AttackPower,
AttackRange = this.AttackRange,
SprintMultiplier = this.SprintMultiplier,
};
}
}

View File

@@ -0,0 +1,36 @@
using LiteNetLib;
using MMOserver.Game.Channel;
using MMOserver.Packet;
using ProtoBuf;
using ServerLib.Packet;
using ServerLib.Service;
namespace MMOserver.Game.Service;
/*
* 플레이어 공격 요청 메시지 핸들러
*/
public partial class GameServer : ServerBase
{
private void OnActionPlayer(NetPeer peer, int 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;
}
Player? player = cm.GetChannel(channelId).GetPlayer(hashKey);
if (player == null)
{
return;
}
// 같은 맵 유저들에게 행동 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.ACTION_PLAYER, packet);
BroadcastToMap(channelId, player.CurrentMapId, data, peer);
}
}

View File

@@ -0,0 +1,86 @@
using LiteNetLib;
using MMOserver.Game.Channel;
using MMOserver.Game.Channel.Maps;
using MMOserver.Packet;
using ProtoBuf;
using Serilog;
using ServerLib.Packet;
using ServerLib.Service;
namespace MMOserver.Game.Service;
/*
* 맵 이동 메시지 핸들러
*/
public partial class GameServer : ServerBase
{
private void OnChangeMap(NetPeer peer, int hashKey, byte[] payload)
{
ChangeMapPacket packet = Serializer.Deserialize<ChangeMapPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
int channelId = cm.HasUser(hashKey);
if (channelId < 0)
{
return;
}
Channel.Channel channel = cm.GetChannel(channelId);
Player? player = channel.GetPlayer(hashKey);
if (player == null)
{
return;
}
int oldMapId = player.CurrentMapId;
int newMapId = packet.MapId;
// 일단 보스맵에서 로비로 원복할떄 캐싱해둔 걸로 교체
if (newMapId == -1)
{
if (player.PreviousMapId > 0)
{
// 레이드 맵 사용 종료 처리
channel.RemoveInstanceMap(oldMapId);
newMapId = player.PreviousMapId;
player.PreviousMapId = 0;
}
}
if (!channel.ChangeMap(hashKey, player, newMapId))
{
Log.Warning("[GameServer] CHANGE_MAP 유효하지 않은 맵 HashKey={Key} MapId={MapId}", hashKey, newMapId);
return;
}
PlayerInfo playerInfo = player.ToPlayerInfo();
// 기존 맵 유저들에게 퇴장 알림
ChangeMapPacket exitNotify = new() { MapId = oldMapId, IsAdd = false, Player = playerInfo };
BroadcastToMap(channelId, oldMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, exitNotify));
// 새 맵 유저들에게 입장 알림 (본인 제외)
ChangeMapPacket enterNotify = new() { MapId = newMapId, IsAdd = true, Player = playerInfo };
BroadcastToMap(channelId, newMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, enterNotify), peer);
// 본인에게 새 맵 플레이어 목록 전달
ChangeMapPacket response = new() { MapId = newMapId };
AMap? newMap = channel.GetMap(newMapId);
if (newMap != null)
{
foreach ((int uid, Player memberPlayer) in newMap.GetUsers())
{
if (uid == hashKey)
{
continue;
}
response.Players.Add(memberPlayer.ToPlayerInfo());
}
}
SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
Log.Debug("[GameServer] CHANGE_MAP HashKey={Key} OldMap={OldMapId} NewMap={MapId}", hashKey, oldMapId, newMapId);
}
}

View File

@@ -0,0 +1,85 @@
using LiteNetLib;
using MMOserver.Game.Channel;
using MMOserver.Game.Party;
using MMOserver.Packet;
using ProtoBuf;
using Serilog;
using ServerLib.Packet;
using ServerLib.Service;
namespace MMOserver.Game.Service;
/*
* 채팅 메시지 핸들러
*/
public partial class GameServer : ServerBase
{
private void OnChat(NetPeer peer, int hashKey, byte[] payload)
{
ChatPacket req = Serializer.Deserialize<ChatPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
int channelId = cm.HasUser(hashKey);
if (channelId < 0)
{
return;
}
Player? sender = cm.GetChannel(channelId).GetPlayer(hashKey);
if (sender == null)
{
return;
}
// 서버에서 발신자 정보 채워줌 (클라 위조 방지)
ChatPacket res = new()
{
Type = req.Type,
SenderId = sender.PlayerId,
SenderNickname = sender.Nickname,
TargetId = req.TargetId,
Message = req.Message
};
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.CHAT, res);
switch (req.Type)
{
case ChatType.GLOBAL:
// 채널 내 모든 유저 (자신 포함)
BroadcastToChannel(channelId, data);
Log.Debug("[Chat] GLOBAL HashKey={Key} Message={Msg}", hashKey, req.Message);
break;
case ChatType.PARTY:
// 파티 멤버에게만 (자신 포함)
PartyManager pm = cm.GetChannel(channelId).GetPartyManager();
PartyInfo? party = pm.GetPartyByPlayer(hashKey);
if (party == null)
{
Log.Warning("[Chat] PARTY 파티 없음 HashKey={Key}", hashKey);
return;
}
BroadcastToUsers(party.PartyMemberIds, data);
Log.Debug("[Chat] PARTY HashKey={Key} PartyId={PartyId} Message={Msg}", hashKey, party.PartyId, req.Message);
break;
case ChatType.WHISPER:
// 대상 + 발신자에게만
if (sessions.TryGetValue(req.TargetId, out NetPeer? targetPeer))
{
SendTo(targetPeer, data);
}
else
{
Log.Warning("[Chat] WHISPER 대상 없음 HashKey={Key} TargetId={TargetId}", hashKey, req.TargetId);
}
// 자신에게도 전송 (귓말 확인용)
SendTo(peer, data);
Log.Debug("[Chat] WHISPER HashKey={Key} TargetId={TargetId} Message={Msg}", hashKey, req.TargetId, req.Message);
break;
}
}
}

View File

@@ -0,0 +1,40 @@
using LiteNetLib;
using MMOserver.Game.Channel;
using MMOserver.Packet;
using ProtoBuf;
using Serilog;
using ServerLib.Service;
namespace MMOserver.Game.Service;
/*
* 채널 나가는 메시지 핸들러
*/
public partial class GameServer : ServerBase
{
private void OnExitChannel(NetPeer peer, int 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;
// 파티 자동 탈퇴
if (channelId >= 0)
{
HandlePartyLeaveOnExit(channelId, hashKey);
}
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);
}
}
}

View File

@@ -0,0 +1,491 @@
using LiteNetLib;
using LiteNetLib.Utils;
using MMOserver.Api;
using MMOserver.Game.Channel;
using MMOserver.Game.Channel.Maps;
using MMOserver.Game.Party;
using MMOserver.Packet;
using MMOserver.Utils;
using ProtoBuf;
using Serilog;
using ServerLib.Packet;
using ServerLib.Service;
namespace MMOserver.Game.Service;
/*
* 주요 게임서버 실행 관리
* - 세션 추가 / 삭제 관리
* - 패킷 핸들러 등록
* - Auth<->Web 인증 관리
* - 같은 Auth 재접속 가능
*/
public partial class GameServer : ServerBase
{
private readonly Dictionary<ushort, Action<NetPeer, int, byte[]>> packetHandlers;
private readonly UuidGenerator userUuidGenerator;
// 동일 토큰 동시 인증 방지
private readonly HashSet<string> authenticatingTokens = new();
public GameServer(int port, string connectionString) : base(port, connectionString)
{
packetHandlers = new Dictionary<ushort, Action<NetPeer, int, byte[]>>
{
[(ushort)PacketCode.INTO_CHANNEL] = OnIntoChannel,
[(ushort)PacketCode.INTO_CHANNEL_PARTY] = OnIntoChannelParty,
[(ushort)PacketCode.EXIT_CHANNEL] = OnExitChannel,
[(ushort)PacketCode.TRANSFORM_PLAYER] = OnTransformPlayer,
[(ushort)PacketCode.ACTION_PLAYER] = OnActionPlayer,
[(ushort)PacketCode.STATE_PLAYER] = OnStatePlayer,
[(ushort)PacketCode.CHANGE_MAP] = OnChangeMap,
[(ushort)PacketCode.PARTY_CHANGE_MAP] = OnPartyChangeMap,
[(ushort)PacketCode.INTO_BOSS_RAID] = OnIntoBossRaid,
[(ushort)PacketCode.REQUEST_PARTY] = OnRequestParty,
[(ushort)PacketCode.CHAT] = OnChat
};
userUuidGenerator = new UuidGenerator();
}
protected override void HandleEcho(NetPeer peer, byte[] payload)
{
if (payload.Length < 4)
{
Log.Warning("[Server] Echo 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
return;
}
// 세션에 넣지는 않는다.
NetDataReader reader = new(payload);
short code = reader.GetShort();
short bodyLength = reader.GetShort();
EchoPacket echoPacket = Serializer.Deserialize<EchoPacket>(payload.AsMemory(4));
Log.Debug("[Echo] : addr={Addr}, str={Str}", peer.Address, echoPacket.Str);
// Echo메시지는 순서보장 안함 HOL Blocking 제거
SendTo(peer, payload, DeliveryMethod.ReliableUnordered);
}
protected override void HandleAuthDummy(NetPeer peer, byte[] payload)
{
DummyAccTokenPacket accTokenPacket = Serializer.Deserialize<DummyAccTokenPacket>(new ReadOnlyMemory<byte>(payload));
int hashKey = accTokenPacket.Token;
if (sessions.TryGetValue(hashKey, out NetPeer? existing))
{
// WiFi → LTE 전환 등 재연결: 이전 피어 교체
existing.Tag = null;
sessions.Remove(hashKey);
Log.Information("[Server] 재연결 HashKey={Key} Old={Old} New={New}", hashKey, existing.Id, peer.Id);
existing.Disconnect();
}
peer.Tag = new Session(hashKey, peer);
sessions[hashKey] = peer;
pendingPeers.Remove(peer.Id);
if (hashKey <= 1000)
{
// 더미 클라다.
ChannelManager cm = ChannelManager.Instance;
Player newPlayer = new()
{
HashKey = hashKey,
PlayerId = hashKey,
Nickname = hashKey.ToString(),
CurrentMapId = 1
};
cm.AddUser(1, hashKey, newPlayer, peer);
}
else
{
Log.Error("[Server] Dummy 클라이언트가 아닙니다. 연결을 종료합니다. HashKey={Key} PeerId={Id}", hashKey, peer.Id);
peer.Disconnect();
return;
}
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
OnSessionConnected(peer, hashKey);
}
protected override async Task HandleAuth(NetPeer peer, byte[] payload)
{
AccTokenPacket accTokenPacket = Serializer.Deserialize<AccTokenPacket>(new ReadOnlyMemory<byte>(payload));
string token = accTokenPacket.Token;
// 동일 토큰 동시 인증 방지
if (!authenticatingTokens.Add(token))
{
Log.Warning("[Server] 동일 토큰 동시 인증 시도 차단 PeerId={Id}", peer.Id);
peer.Disconnect();
return;
}
try
{
string? username = "";
int hashKey;
bool isReconnect;
lock (sessionLock)
{
isReconnect = tokenHash.TryGetValue(token, out hashKey) && hashKey > 1000;
if (!isReconnect)
{
hashKey = userUuidGenerator.Create();
}
if (isReconnect && sessions.TryGetValue(hashKey, out NetPeer? existing))
{
// WiFi → LTE 전환 등 재연결: 이전 피어 교체 (토큰 재검증 불필요)
existing.Tag = null;
sessions.Remove(hashKey);
Log.Information("[Server] 재연결 HashKey={Key} Old={Old} New={New}", hashKey, existing.Id, peer.Id);
existing.Disconnect();
}
}
if (!isReconnect)
{
// 신규 연결: 웹서버에 JWT 검증 요청
username = await RestApi.Instance.VerifyTokenAsync(token);
if (username == null)
{
Log.Warning("[Server] 토큰 검증 실패 - 연결 거부 PeerId={Id}", peer.Id);
userUuidGenerator.Release(hashKey);
peer.Disconnect();
return;
}
Log.Information("[Server] 토큰 검증 성공 Username={Username} PeerId={Id}", username, peer.Id);
}
// await 이후 — 공유 자원 접근 보호
lock (sessionLock)
{
peer.Tag = new Session(hashKey, peer);
((Session)peer.Tag).Token = token;
if (username.Length > 0)
{
((Session)peer.Tag).Username = username;
}
sessions[hashKey] = peer;
tokenHash[token] = hashKey;
pendingPeers.Remove(peer.Id);
}
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
OnSessionConnected(peer, hashKey);
}
finally
{
authenticatingTokens.Remove(token);
}
}
protected override void OnSessionConnected(NetPeer peer, int hashKey)
{
Log.Information("[GameServer] 세션 연결 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
// 만약 wifi-lte 로 바꿔졌다 이때 이미 로비에 들어가 있다면 넘긴다.
ChannelManager cm = ChannelManager.Instance;
int channelId = cm.HasUser(hashKey);
if (channelId >= 0)
{
// 재연결: Channel 내 peer 참조 갱신 후 채널 유저 목록 전송
cm.GetChannel(channelId).UpdatePeer(hashKey, peer);
SendIntoChannelPacket(peer, hashKey);
}
else
{
// 모든 채널 정보 던진다
SendLoadChannelPacket(peer, hashKey);
}
}
protected override void OnSessionDisconnected(NetPeer peer, int hashKey, DisconnectInfo info)
{
ChannelManager cm = ChannelManager.Instance;
// 제거 전에 채널/플레이어 정보 저장 (브로드캐스트에 필요)
int channelId = cm.HasUser(hashKey);
Player? player = channelId >= 0 ? cm.GetChannel(channelId).GetPlayer(hashKey) : null;
// 퇴장 시 위치/플레이타임 DB 저장 (fire-and-forget)
if (player != null && peer.Tag is Session session && session.Username != null)
{
long playTimeDelta = 0;
if (session.ChannelJoinedAt != default)
{
playTimeDelta = (long)(DateTime.UtcNow - session.ChannelJoinedAt).TotalSeconds;
}
_ = RestApi.Instance.SaveGameDataAsync(
session.Username,
player.PosX, player.PosY, player.PosZ, player.RotY,
playTimeDelta > 0 ? playTimeDelta : null
);
}
if (cm.RemoveUser(hashKey))
{
Log.Information("[GameServer] 세션 해제 HashKey={Key} Reason={Reason}", hashKey, info.Reason);
if (channelId >= 0 && player != null)
{
// 파티 자동 탈퇴
HandlePartyLeaveOnExit(channelId, hashKey);
// 같은 채널 유저들에게 나갔다고 알림
SendExitChannelPacket(peer, hashKey, channelId, player);
}
}
userUuidGenerator.Release(hashKey);
}
protected override void HandlePacket(NetPeer peer, int hashKey, ushort type, byte[] payload)
{
if (packetHandlers.TryGetValue(type, out Action<NetPeer, int, byte[]>? handler))
{
try
{
handler(peer, hashKey, payload);
}
catch (Exception ex)
{
Log.Error(ex, "[GameServer] 패킷 처리 중 예외 Type={Type} HashKey={Key}", type, hashKey);
}
}
else
{
Log.Warning("[GameServer] 알 수 없는 패킷 Type={Type}", type);
}
}
// 보내는 패킷
private void SendLoadChannelPacket(NetPeer peer, int hashKey)
{
LoadChannelPacket loadChannelPacket = new();
foreach (Channel.Channel channel in ChannelManager.Instance.GetChannels().Values)
{
if (channel.ChannelId <= 0)
{
continue;
}
if (channel.ChannelId >= 1000)
{
continue;
}
ChannelInfo info = new();
info.ChannelId = channel.ChannelId;
info.ChannelUserCount = channel.UserCount;
info.ChannelUserMax = channel.UserCountMax;
loadChannelPacket.Channels.Add(info);
}
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.LOAD_CHANNEL, loadChannelPacket);
SendTo(peer, data);
}
// 나간 유저를 같은 채널 유저들에게 알림 (UPDATE_CHANNEL_USER IsAdd=false)
private void SendExitChannelPacket(NetPeer peer, int hashKey, int channelId, Player player)
{
UpdateChannelUserPacket packet = new()
{
Players = player.ToPlayerInfo(),
IsAdd = false
};
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_CHANNEL_USER, packet);
// 이미 채널에서 제거된 후라 나간 본인에게는 전송되지 않음
BroadcastToChannel(channelId, data);
}
// 채널 입장 시 패킷 전송
// - 새 유저에게 : 기존 채널 유저 목록 (INTO_CHANNEL)
// - 기존 유저들에게 : 새 유저 입장 알림 (UPDATE_CHANNEL_USER IsAdd=true)
private void SendIntoChannelPacket(NetPeer peer, int 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() { ChannelId = channelId };
foreach (int userId in channel.GetConnectUsers())
{
if (userId == hashKey)
{
continue;
}
Player? channelPlayer = channel.GetPlayer(userId);
if (channelPlayer != null)
{
response.Players.Add(channelPlayer.ToPlayerInfo());
}
}
foreach (PartyInfo party in channel.GetPartyManager().GetAllParties())
{
response.Parties.Add(new PartyInfoData
{
PartyId = party.PartyId,
LeaderId = party.LeaderId,
MemberPlayerIds = new List<int>(party.PartyMemberIds),
PartyName = party.PartyName
});
}
byte[] toNewUser = PacketSerializer.Serialize((ushort)PacketCode.INTO_CHANNEL, response);
SendTo(peer, toNewUser);
// 2. 기존 유저들에게: 새 유저 입장 알림
if (myPlayer != null)
{
UpdateChannelUserPacket notify = new()
{
Players = myPlayer.ToPlayerInfo(),
IsAdd = true
};
byte[] toOthers = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_CHANNEL_USER, notify);
BroadcastToChannel(channelId, toOthers, peer);
}
}
// 채널 입장 시 패킷 전송
// - 자신 유저에게 : 내 정보 (LOAD_GAME)
private void SendLoadGame(NetPeer peer, int hashKey)
{
ChannelManager cm = ChannelManager.Instance;
int channelId = cm.HasUser(hashKey);
Player? player = channelId >= 0 ? cm.GetChannel(channelId).GetPlayer(hashKey) : null;
if (player == null)
{
Log.Warning("[GameServer] LOAD_GAME 플레이어 없음 HashKey={Key}", hashKey);
byte[] denied =
PacketSerializer.Serialize((ushort)PacketCode.LOAD_GAME, new LoadGamePacket { IsAccepted = false });
SendTo(peer, denied);
return;
}
LoadGamePacket packet = new()
{
IsAccepted = true,
Player = player.ToPlayerInfo(),
MapId = player.CurrentMapId
};
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.LOAD_GAME, packet);
SendTo(peer, data);
Log.Debug("[GameServer] LOAD_GAME HashKey={Key} PlayerId={PlayerId} ChannelId={ChannelId}", hashKey, player.PlayerId, channelId);
}
/*
* 채널 브로드캐스트 헬퍼
*/
// 특정 채널의 모든 유저에게 전송 (exclude 지정 시 해당 피어 제외) / Channel이 NetPeer를 직접 보유하므로 sessions 교차 조회 없음
private void BroadcastToChannel(int channelId, byte[] data, NetPeer? exclude = null,
DeliveryMethod method = DeliveryMethod.ReliableOrdered)
{
Channel.Channel channel = ChannelManager.Instance.GetChannel(channelId);
foreach (NetPeer targetPeer in channel.GetConnectPeers())
{
if (exclude != null && targetPeer.Id == exclude.Id)
{
continue;
}
SendTo(targetPeer, data, method);
}
}
// 특정 맵의 유저들에게 전송 (exclude 지정 시 해당 피어 제외)
private void BroadcastToMap(int channelId, int mapId, byte[] data, NetPeer? exclude = null, DeliveryMethod method = DeliveryMethod.ReliableOrdered)
{
AMap? map = ChannelManager.Instance.GetChannel(channelId).GetMap(mapId);
if (map == null)
{
return;
}
foreach (int userId in map.GetUsers().Keys)
{
if (!sessions.TryGetValue(userId, out NetPeer? targetPeer))
{
continue;
}
if (exclude != null && targetPeer.Id == exclude.Id)
{
continue;
}
SendTo(targetPeer, data, method);
}
}
// 채널 퇴장/연결 해제 시 파티 자동 탈퇴 처리
private void HandlePartyLeaveOnExit(int channelId, int hashKey)
{
PartyManager pm = ChannelManager.Instance.GetChannel(channelId).GetPartyManager();
int? partyId = pm.GetPartyByPlayer(hashKey)?.PartyId;
if (partyId == null)
{
return; // 파티에 없으면 무시
}
pm.LeaveParty(hashKey, out PartyInfo? remaining);
// 남은 멤버 있음 → LEAVE, 0명(파티 해산됨) → DELETE
UpdatePartyPacket notify = remaining != null && remaining.PartyMemberIds.Count > 0
? new UpdatePartyPacket
{
PartyId = partyId.Value,
Type = PartyUpdateType.LEAVE,
LeaderId = remaining.LeaderId,
PlayerId = hashKey
}
: new UpdatePartyPacket
{
PartyId = partyId.Value,
Type = PartyUpdateType.DELETE,
LeaderId = -1,
PlayerId = hashKey
};
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, notify);
BroadcastToChannel(channelId, data);
}
private void BroadcastToUsers(IEnumerable<int> userIds, byte[] data, DeliveryMethod method = DeliveryMethod.ReliableOrdered)
{
foreach (int userId in userIds)
{
if (sessions.TryGetValue(userId, out NetPeer? targetPeer))
{
SendTo(targetPeer, data, method);
}
}
}
private void SendError(NetPeer peer, ErrorCode code)
{
ErrorPacket err = new() { Code = code };
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.ERROR, err);
SendTo(peer, data);
}
}

View File

@@ -0,0 +1,169 @@
using LiteNetLib;
using MMOserver.Api;
using MMOserver.Game.Channel;
using MMOserver.Game.Channel.Maps;
using MMOserver.Game.Party;
using MMOserver.Packet;
using ProtoBuf;
using Serilog;
using ServerLib.Packet;
using ServerLib.Service;
namespace MMOserver.Game.Service;
/*
* 보스레이드 접속 메시지 핸들러
*/
public partial class GameServer : ServerBase
{
private async void OnIntoBossRaid(NetPeer peer, int hashKey, byte[] payload)
{
try
{
IntoBossRaidPacket packet = Serializer.Deserialize<IntoBossRaidPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
int channelId = cm.HasUser(hashKey);
if (channelId < 0)
{
return;
}
Channel.Channel channel = cm.GetChannel(channelId);
// 파티 조회
PartyInfo? party = channel.GetPartyManager().GetPartyByPlayer(hashKey);
if (party == null)
{
Log.Warning("[GameServer] INTO_BOSS_RAID 파티 없음 HashKey={Key}", hashKey);
SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket { RaidId = packet.RaidId, IsSuccess = false, Reason = "파티에 속해있지 않습니다." }));
return;
}
// 파티장만 요청 가능
if (party.LeaderId != hashKey)
{
Log.Warning("[GameServer] INTO_BOSS_RAID 파티장 아님 HashKey={Key} LeaderId={LeaderId}", hashKey, party.LeaderId);
SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket { RaidId = packet.RaidId, IsSuccess = false, Reason = "파티장만 보스 레이드를 시작할 수 있습니다." }));
return;
}
// API로 접속 체크
List<string> userNames = new List<string>();
foreach (int memberId in party.PartyMemberIds)
{
Player? memberPlayer = channel.GetPlayer(memberId);
if (memberPlayer != null)
{
userNames.Add(memberPlayer.Nickname);
}
}
BossRaidResult? result = await RestApi.Instance.BossRaidAccessAsync(userNames, packet.RaidId);
// await 이후 — 공유 자원 접근 보호
lock (sessionLock)
{
// 입장 실패
if (result == null || result.BossId <= 0)
{
SendTo(peer,
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket { RaidId = -1, IsSuccess = false, Reason = "보스 레이드 방을 배정받지 못했습니다. 잠시 후 다시 시도해주세요." }));
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId} Failed", hashKey,
party.PartyId, -1);
return;
}
// await 이후 상태 재검증
channelId = cm.HasUser(hashKey);
if (channelId < 0)
{
return;
}
channel = cm.GetChannel(channelId);
party = channel.GetPartyManager().GetPartyByPlayer(hashKey);
if (party == null)
{
return;
}
// 레이드 맵 할당 (미사용 맵 탐색 → 없으면 동적 생성)
int assignedRaidMapId = channel.GetOrCreateAvailableRaidMap();
// 진행중 맵으로 등록
channel.AddInstanceMap(assignedRaidMapId);
// 파티원 전체 레이드 맵으로 이동 + 각자에게 알림
foreach (int memberId in party.PartyMemberIds)
{
Player? memberPlayer = channel.GetPlayer(memberId);
if (memberPlayer == null)
{
continue;
}
// 이전 맵 캐싱 (레이드 종료 후 복귀용)
memberPlayer.PreviousMapId = memberPlayer.CurrentMapId;
int oldMapId = memberPlayer.CurrentMapId;
channel.ChangeMap(memberId, memberPlayer, assignedRaidMapId);
if (!sessions.TryGetValue(memberId, out NetPeer? memberPeer))
{
continue;
}
PlayerInfo memberInfo = memberPlayer.ToPlayerInfo();
// 기존 맵 유저들에게 퇴장 알림
ChangeMapPacket exitNotify = new() { MapId = oldMapId, IsAdd = false, Player = memberInfo };
BroadcastToMap(channelId, oldMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, exitNotify));
// 새 맵 유저들에게 입장 알림 (본인 제외)
ChangeMapPacket enterNotify = new() { MapId = assignedRaidMapId, IsAdd = true, Player = memberInfo };
BroadcastToMap(channelId, assignedRaidMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, enterNotify),
memberPeer);
// 본인에게 새 맵 플레이어 목록 전달
ChangeMapPacket response = new() { MapId = assignedRaidMapId };
AMap? raidMap = channel.GetMap(assignedRaidMapId);
if (raidMap != null)
{
foreach ((int uid, Player channelPlayer) in raidMap.GetUsers())
{
if (uid != memberId)
{
response.Players.Add(channelPlayer.ToPlayerInfo());
}
}
}
SendTo(memberPeer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
// 각 파티원에게 레이드 입장 결과 전달 (Session, Token 포함)
SendTo(memberPeer,
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket
{
RaidId = assignedRaidMapId, IsSuccess = true, Session = result.SessionName,
Token = result.Tokens != null && result.Tokens.TryGetValue(memberPlayer.Nickname, out string? memberToken)
? memberToken
: ""
}));
}
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId}", hashKey, party.PartyId,
assignedRaidMapId);
}
}
catch (Exception e)
{
Log.Warning($"[GameServer] Error : {e.Message}");
}
}
}

View File

@@ -0,0 +1,159 @@
using LiteNetLib;
using MMOserver.Api;
using MMOserver.Game.Channel;
using MMOserver.Game.Channel.Maps;
using MMOserver.Packet;
using ProtoBuf;
using Serilog;
using ServerLib.Packet;
using ServerLib.Service;
namespace MMOserver.Game.Service;
/*
* 채널 접속 요청 메시지 핸들러
*/
public partial class GameServer : ServerBase
{
private async void OnIntoChannel(NetPeer peer, int hashKey, byte[] payload)
{
try
{
IntoChannelPacket packet = Serializer.Deserialize<IntoChannelPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
// 이전에 다른 채널에 있었는지 체크
int preChannelId = cm.HasUser(hashKey);
Player? prevPlayer = preChannelId >= 0 ? cm.GetChannel(preChannelId).GetPlayer(hashKey) : null;
if (preChannelId >= 0)
{
Player? player = prevPlayer;
// 파티 자동 탈퇴
HandlePartyLeaveOnExit(preChannelId, hashKey);
cm.RemoveUser(hashKey);
Log.Debug("[GameServer] EXIT_CHANNEL HashKey={Key} PlayerId={PlayerId}", hashKey, preChannelId);
// 같은 채널 유저들에게 나갔다고 알림
if (player != null)
{
SendExitChannelPacket(peer, hashKey, preChannelId, player);
}
}
Channel.Channel newChannel = cm.GetChannel(packet.ChannelId);
// 최대 인원 체크
if (newChannel.UserCount >= newChannel.UserCountMax)
{
Log.Warning("[GameServer] INTO_CHANNEL 채널 인원 초과 HashKey={Key} ChannelId={ChannelId} UserCount={Count}/{Max}",
hashKey, packet.ChannelId, newChannel.UserCount, newChannel.UserCountMax);
// 이전 채널에서 이미 제거된 경우 → 이전 채널로 복귀
if (preChannelId >= 0 && prevPlayer != null)
{
cm.AddUser(preChannelId, hashKey, prevPlayer, peer);
Log.Information("[GameServer] INTO_CHANNEL 만석 → 이전 채널({ChannelId})로 복귀 HashKey={Key}", preChannelId, hashKey);
}
byte[] full = PacketSerializer.Serialize((ushort)PacketCode.INTO_CHANNEL,
new IntoChannelPacket { ChannelId = -1 });
SendTo(peer, full);
return;
}
// 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;
newPlayer.PosX = (float)profile.LastPosX;
newPlayer.PosY = (float)profile.LastPosY;
newPlayer.PosZ = (float)profile.LastPosZ;
newPlayer.RotY = (float)profile.LastRotY;
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);
}
}
// 채널 입장 시각 기록 (플레이타임 계산용)
((Session)peer.Tag).ChannelJoinedAt = DateTime.UtcNow;
// 채널에 추가
cm.AddUser(packet.ChannelId, hashKey, newPlayer, peer);
Log.Debug("[GameServer] INTO_CHANNEL HashKey={Key} ChannelId={ChannelId}", hashKey, packet.ChannelId);
// 접속된 모든 유저 정보 전달
SendIntoChannelPacket(peer, hashKey);
// 내 정보 전달
SendLoadGame(peer, hashKey);
// 초기 맵(로비 1번) 진입 알림
// Channel.AddUser → ChangeMap(1) 에서 이미 맵에 추가됨
PlayerInfo playerInfo = newPlayer.ToPlayerInfo();
int initMapId = newPlayer.CurrentMapId;
// 기존 맵 유저들에게 입장 알림 (본인 제외)
ChangeMapPacket enterNotify = new() { MapId = initMapId, IsAdd = true, Player = playerInfo };
BroadcastToMap(packet.ChannelId, initMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, enterNotify), peer);
// 본인에게 현재 맵의 플레이어 목록 전달
ChangeMapPacket response = new() { MapId = initMapId };
AMap? initMap = newChannel.GetMap(initMapId);
if (initMap != null)
{
foreach (var (userId, channelPlayer) in initMap.GetUsers())
{
if (userId == hashKey)
{
continue;
}
response.Players.Add(channelPlayer.ToPlayerInfo());
}
}
SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
}
catch (Exception e)
{
Log.Warning($"[GameServer] Error : {e.Message}");
}
}
}

View File

@@ -0,0 +1,140 @@
using LiteNetLib;
using MMOserver.Game.Channel;
using MMOserver.Game.Party;
using MMOserver.Packet;
using ProtoBuf;
using Serilog;
using ServerLib.Packet;
using ServerLib.Service;
namespace MMOserver.Game.Service;
/*
* 파티 안뒤 채널 이동 메시지 핸들러
*/
public partial class GameServer : ServerBase
{
private void OnIntoChannelParty(NetPeer peer, int hashKey, byte[] payload)
{
IntoChannelPartyPacket packet = Serializer.Deserialize<IntoChannelPartyPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
int preChannelId = cm.HasUser(hashKey);
// 이전에 다른 채널에 있었는지 체크 / 파티이동은 이미 접속한 상태여야 한다.
if (preChannelId < 0)
{
Log.Warning("[GameServer] INTO_CHANNEL_PARTY 채널에 접속하지 않은 유저");
return;
}
Channel.Channel preChannel = cm.GetChannel(preChannelId);
Channel.Channel newChannel = cm.GetChannel(packet.ChannelId);
PartyInfo? preParty = preChannel.GetPartyManager().GetParty(packet.PartyId);
if (preParty == null)
{
Log.Warning("[GameServer] INTO_CHANNEL_PARTY 해당 파티 없음");
return;
}
// 새로운 파티를 복사한다
PartyInfo tempParty = new();
tempParty.DeepCopySemi(preParty);
// 최대 인원 체크
if (newChannel.UserCount + preParty.PartyMemberIds.Count >= newChannel.UserCountMax)
{
Log.Warning("[GameServer] INTO_CHANNEL_PARTY 채널 인원 초과 HashKey={Key} ChannelId={ChannelId} UserCount={Count}/{Max}",
hashKey, packet.ChannelId, newChannel.UserCount, newChannel.UserCountMax);
byte[] full = PacketSerializer.Serialize((ushort)PacketCode.INTO_CHANNEL,
new IntoChannelPacket { ChannelId = -1 });
SendTo(peer, full);
return;
}
// 기존 채널에서 제거 전에 플레이어 정보 보존
Dictionary<int, Player> savedPlayers = new();
foreach (int memberId in preParty.PartyMemberIds)
{
Player? player = preChannel.GetPlayer(memberId);
if (player != null)
{
savedPlayers[memberId] = player;
UpdateChannelUserPacket exitNotify = new()
{
Players = player.ToPlayerInfo(),
IsAdd = false
};
byte[] exitData = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_CHANNEL_USER, exitNotify);
BroadcastToChannel(preChannelId, exitData);
// 이전 채널에서 제거
preChannel.RemoveUser(memberId);
// 현재 존재하는 파티원만 추가한다.
tempParty.PartyMemberIds.Add(memberId);
}
}
// 이전채널에서 파티를 지운다.
preChannel.GetPartyManager().DeleteParty(hashKey, packet.PartyId, out preParty);
UpdatePartyPacket notify = new()
{
PartyId = preParty!.PartyId,
Type = PartyUpdateType.DELETE,
LeaderId = preParty.LeaderId
};
// 채널 전체 파티 목록 갱신
BroadcastToChannel(preChannelId, PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, notify));
// 새로운 채널에 파티원 넣기
foreach (int memberId in tempParty.PartyMemberIds)
{
sessions.TryGetValue(memberId, out NetPeer? memberPeer);
if (memberPeer != null)
{
// 새 채널에 유저 추가 (보존된 플레이어 정보 사용)
string nickname = savedPlayers.TryGetValue(memberId, out Player? saved) ? saved.Nickname : memberId.ToString();
Player newPlayer = new()
{
HashKey = memberId,
PlayerId = memberId,
Nickname = nickname
};
cm.AddUser(packet.ChannelId, memberId, newPlayer, memberPeer);
// 접속된 모든 유저 정보 전달
SendIntoChannelPacket(memberPeer, memberId);
// 내 정보 전달
SendLoadGame(memberPeer, memberId);
}
}
// 새로운 채널에 파티를 추가한다.
if (newChannel.GetPartyManager()
.CreateParty(tempParty.LeaderId, tempParty.PartyName, out PartyInfo? createdParty, tempParty.PartyMemberIds) &&
createdParty != null)
{
// 새 채널 기존 유저들에게 파티 생성 알림
UpdatePartyPacket createNotify = new()
{
PartyId = createdParty.PartyId,
Type = PartyUpdateType.CREATE,
LeaderId = createdParty.LeaderId,
PartyName = createdParty.PartyName
};
BroadcastToChannel(packet.ChannelId,
PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, createNotify));
}
else
{
Log.Warning("[GameServer] 파티생성 실패 !!!");
}
}
}

View File

@@ -0,0 +1,95 @@
using LiteNetLib;
using MMOserver.Game.Channel;
using MMOserver.Game.Channel.Maps;
using MMOserver.Game.Party;
using MMOserver.Packet;
using ProtoBuf;
using Serilog;
using ServerLib.Packet;
using ServerLib.Service;
namespace MMOserver.Game.Service;
/*
* 파티단위 맵 이동 메시지 핸들러
*/
public partial class GameServer : ServerBase
{
private void OnPartyChangeMap(NetPeer peer, int hashKey, byte[] payload)
{
PartyChangeMapPacket packet = Serializer.Deserialize<PartyChangeMapPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
int channelId = cm.HasUser(hashKey);
if (channelId < 0)
{
return;
}
Channel.Channel channel = cm.GetChannel(channelId);
// 맵 유효성 체크
if (channel.GetMap(packet.MapId) == null)
{
Log.Warning("[GameServer] PARTY_CHANGE_MAP 유효하지 않은 맵 HashKey={Key} MapId={MapId}", hashKey, packet.MapId);
return;
}
// 파티 확인
PartyInfo? party = channel.GetPartyManager().GetParty(packet.PartyId);
if (party == null)
{
Log.Warning("[GameServer] PARTY_CHANGE_MAP 파티 없음 HashKey={Key} PartyId={PartyId}", hashKey, packet.PartyId);
return;
}
// 파티원 전체 맵 이동 + 각자에게 알림
foreach (int memberId in party.PartyMemberIds)
{
Player? memberPlayer = channel.GetPlayer(memberId);
if (memberPlayer == null)
{
continue;
}
int oldMapId = memberPlayer.CurrentMapId;
channel.ChangeMap(memberId, memberPlayer, packet.MapId);
if (!sessions.TryGetValue(memberId, out NetPeer? memberPeer))
{
continue;
}
PlayerInfo memberInfo = memberPlayer.ToPlayerInfo();
// 기존 맵 유저들에게 퇴장 알림
ChangeMapPacket exitNotify = new() { MapId = oldMapId, IsAdd = false, Player = memberInfo };
BroadcastToMap(channelId, oldMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, exitNotify));
// 새 맵 유저들에게 입장 알림 (본인 제외)
ChangeMapPacket enterNotify = new() { MapId = packet.MapId, IsAdd = true, Player = memberInfo };
BroadcastToMap(channelId, packet.MapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, enterNotify), memberPeer);
// 본인에게 새 맵 플레이어 목록 전달
ChangeMapPacket response = new() { MapId = packet.MapId };
AMap? newMap = channel.GetMap(packet.MapId);
if (newMap != null)
{
foreach ((int uid, Player player) in newMap.GetUsers())
{
if (uid == memberId)
{
continue;
}
response.Players.Add(player.ToPlayerInfo());
}
}
SendTo(memberPeer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
}
Log.Debug("[GameServer] PARTY_CHANGE_MAP HashKey={Key} PartyId={PartyId} MapId={MapId}", hashKey, packet.PartyId, packet.MapId);
}
}

View File

@@ -0,0 +1,212 @@
using LiteNetLib;
using MMOserver.Game.Channel;
using MMOserver.Game.Party;
using MMOserver.Packet;
using ProtoBuf;
using ServerLib.Packet;
using ServerLib.Service;
namespace MMOserver.Game.Service;
/*
* 파티 요청(추가, 탈퇴, 정보변경) 메시지 핸들러
*/
public partial class GameServer : ServerBase
{
private void OnRequestParty(NetPeer peer, int hashKey, byte[] payload)
{
RequestPartyPacket req = Serializer.Deserialize<RequestPartyPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
int channelId = cm.HasUser(hashKey);
if (channelId < 0)
{
return;
}
PartyManager pm = cm.GetChannel(channelId).GetPartyManager();
switch (req.Type)
{
case PartyUpdateType.CREATE:
{
if (!pm.CreateParty(hashKey, req.PartyName, out PartyInfo? party))
{
SendError(peer, ErrorCode.PARTY_ALREADY_IN_PARTY);
return;
}
UpdatePartyPacket notify = new()
{
PartyId = party!.PartyId,
Type = PartyUpdateType.CREATE,
LeaderId = party.LeaderId,
PlayerId = hashKey,
PartyName = party.PartyName
};
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, notify);
BroadcastToChannel(channelId, data); // 채널 전체 파티 목록 갱신
break;
}
case PartyUpdateType.JOIN:
{
if (!pm.JoinParty(hashKey, req.PartyId, out PartyInfo? party))
{
SendError(peer, ErrorCode.PARTY_JOIN_FAILED);
return;
}
UpdatePartyPacket notify = new()
{
PartyId = party!.PartyId,
Type = PartyUpdateType.JOIN,
LeaderId = party.LeaderId,
PlayerId = hashKey
};
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, notify);
BroadcastToChannel(channelId, data); // 채널 전체 파티 목록 갱신
break;
}
case PartyUpdateType.LEAVE:
{
if (!pm.LeaveParty(hashKey, out PartyInfo? party) || party == null)
{
SendError(peer, ErrorCode.PARTY_NOT_IN_PARTY);
return;
}
UpdatePartyPacket notify = new()
{
PartyId = party.PartyId, Type = PartyUpdateType.DELETE, LeaderId = party.LeaderId, PlayerId = hashKey
};
// 파티가 남아있으면 살린다.
if (party.PartyMemberIds.Count > 0)
{
notify.Type = PartyUpdateType.LEAVE;
}
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, notify);
BroadcastToChannel(channelId, data); // 채널 전체 파티 목록 갱신 (탈퇴자 포함)
break;
}
case PartyUpdateType.DELETE:
{
if (!pm.DeleteParty(hashKey, req.PartyId, out PartyInfo? party))
{
SendError(peer, ErrorCode.PARTY_DELETE_FAILED);
return;
}
UpdatePartyPacket notify = new()
{
PartyId = party!.PartyId,
Type = PartyUpdateType.DELETE,
LeaderId = party.LeaderId
};
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, notify);
BroadcastToChannel(channelId, data); // 채널 전체 파티 목록 갱신
break;
}
case PartyUpdateType.UPDATE:
{
if (!pm.UpdateParty(hashKey, req.PartyId, req.PartyName, out PartyInfo? party))
{
SendError(peer, ErrorCode.PARTY_UPDATE_FAILED);
return;
}
UpdatePartyPacket notify = new()
{
PartyId = req.PartyId,
Type = PartyUpdateType.UPDATE,
LeaderId = party?.LeaderId ?? 0,
PlayerId = hashKey,
PartyName = req.PartyName
};
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, notify);
BroadcastToChannel(channelId, data); // 채널 전체 파티 목록 갱신
break;
}
case PartyUpdateType.INVITE:
{
// 리더만 초대 가능
PartyInfo? myParty = pm.GetPartyByPlayer(hashKey);
if (myParty == null || myParty.LeaderId != hashKey)
{
SendError(peer, ErrorCode.PARTY_JOIN_FAILED);
return;
}
if (myParty.GetPartyMemberCount() >= PartyInfo.partyMemberMax)
{
SendError(peer, ErrorCode.PARTY_JOIN_FAILED);
return;
}
// 대상 플레이어가 같은 채널에 있는지 확인
int targetId = req.TargetPlayerId;
Channel.Channel? ch = cm.GetChannel(channelId);
if (ch == null || ch.GetPlayer(targetId) == null)
{
SendError(peer, ErrorCode.PARTY_JOIN_FAILED);
return;
}
// 대상에게 초대 알림 전송
NetPeer? targetPeer = ch.GetPeer(targetId);
if (targetPeer == null)
{
SendError(peer, ErrorCode.PARTY_JOIN_FAILED);
return;
}
UpdatePartyPacket inviteNotify = new()
{
PartyId = myParty.PartyId,
Type = PartyUpdateType.INVITE,
LeaderId = hashKey,
PlayerId = targetId,
PartyName = myParty.PartyName
};
byte[] inviteData = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, inviteNotify);
SendTo(targetPeer, inviteData);
break;
}
case PartyUpdateType.KICK:
{
// 리더만 추방 가능
PartyInfo? myParty2 = pm.GetPartyByPlayer(hashKey);
if (myParty2 == null || myParty2.LeaderId != hashKey)
{
SendError(peer, ErrorCode.PARTY_DELETE_FAILED);
return;
}
int kickTarget = req.TargetPlayerId;
if (kickTarget == hashKey)
{
return; // 자기 자신은 추방 불가
}
if (!pm.LeaveParty(kickTarget, out PartyInfo? kickedParty) || kickedParty == null)
{
SendError(peer, ErrorCode.PARTY_NOT_IN_PARTY);
return;
}
UpdatePartyPacket kickNotify = new()
{
PartyId = kickedParty.PartyId,
Type = PartyUpdateType.KICK,
LeaderId = kickedParty.LeaderId,
PlayerId = kickTarget
};
byte[] kickData = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, kickNotify);
BroadcastToChannel(channelId, kickData);
break;
}
}
}
}

View File

@@ -0,0 +1,42 @@
using LiteNetLib;
using MMOserver.Game.Channel;
using MMOserver.Packet;
using ProtoBuf;
using ServerLib.Packet;
using ServerLib.Service;
namespace MMOserver.Game.Service;
/*
* 채널 내 플레이어 정보 갱신 메시지 핸들러
*/
public partial class GameServer : ServerBase
{
private void OnStatePlayer(NetPeer peer, int 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)
{
return;
}
player.Hp = packet.Hp;
player.MaxHp = packet.MaxHp;
player.Mp = packet.Mp;
player.MaxMp = packet.MaxMp;
// 같은 맵 유저들에게 스테이트 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.STATE_PLAYER, packet);
BroadcastToMap(channelId, player.CurrentMapId, data, peer);
}
}

View File

@@ -0,0 +1,42 @@
using LiteNetLib;
using MMOserver.Game.Channel;
using MMOserver.Packet;
using ProtoBuf;
using ServerLib.Packet;
using ServerLib.Service;
namespace MMOserver.Game.Service;
/*
* 플레이어 위치/방향 업데이트 핸들러
*/
public partial class GameServer : ServerBase
{
private void OnTransformPlayer(NetPeer peer, int 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)
{
return;
}
player.PosX = packet.Position.X;
player.PosY = packet.Position.Y;
player.PosZ = packet.Position.Z;
player.RotY = packet.RotY;
// 같은 맵 유저들에게 위치/방향 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.TRANSFORM_PLAYER, packet);
BroadcastToMap(channelId, player.CurrentMapId, data, peer, DeliveryMethod.Unreliable);
}
}

View File

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

View File

@@ -4,12 +4,28 @@ using ProtoBuf;
namespace MMOserver.Packet;
// ============================================================
// 에코용
// ============================================================
// ECHO
[ProtoContract]
public class EchoPacket
{
[ProtoMember(1)]
public string Str
{
get;
set;
}
}
// ============================================================
// 공통 타입
// ============================================================
[ProtoContract]
public class Vector3
public class Position
{
[ProtoMember(1)]
public float X
@@ -86,7 +102,7 @@ public class PlayerInfo
}
[ProtoMember(8)]
public Vector3 Position
public Position Position
{
get;
set;
@@ -98,15 +114,62 @@ public class PlayerInfo
get;
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;
}
}
// ============================================================
// 인증
// ============================================================
// RECV_TOKEN
// DUMMY_ACC_TOKEN
[ProtoContract]
public class RecvTokenPacket
public class DummyAccTokenPacket
{
[ProtoMember(1)]
public int Token
{
get;
set;
}
}
// ACC_TOKEN
[ProtoContract]
public class AccTokenPacket
{
[ProtoMember(1)]
public string Token
@@ -135,7 +198,7 @@ public class LoadGamePacket
}
[ProtoMember(3)]
public int MaplId
public int MapId
{
get;
set;
@@ -157,7 +220,7 @@ public class ChannelInfo
}
[ProtoMember(2)]
public int ChannelUserConut
public int ChannelUserCount
{
get;
set;
@@ -182,6 +245,39 @@ public class LoadChannelPacket
} = 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 / 서버->클라: 채널 내 나 이외 플레이어 목록
[ProtoContract]
public class IntoChannelPacket
@@ -199,6 +295,47 @@ public class IntoChannelPacket
get;
set;
} = 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 유저 접속/나감
@@ -259,7 +396,7 @@ public class TransformPlayerPacket
}
[ProtoMember(2)]
public Vector3 Position
public Position Position
{
get;
set;
@@ -371,7 +508,7 @@ public class TransformNpcPacket
}
[ProtoMember(2)]
public Vector3 Position
public Position Position
{
get;
set;
@@ -488,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;
}
}
// ============================================================
// 파티
// ============================================================
@@ -495,16 +658,210 @@ public class DamagePacket
public enum PartyUpdateType
{
CREATE,
DELETE
}
public enum UserPartyUpdateType
{
DELETE,
JOIN,
LEAVE
LEAVE,
UPDATE,
INVITE, // 리더가 대상 플레이어에게 초대 전송
KICK // 리더가 파티원을 추방
}
// 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 시 사용
[ProtoMember(4)]
public int TargetPlayerId
{
get;
set;
} // INVITE, KICK 시 사용
}
// ============================================================
// 채팅
// ============================================================
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;
}
// 실패 사유 (서버 -> 클라, IsSuccess == false 시)
[ProtoMember(5)]
public string Reason
{
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]
public class UpdatePartyPacket
{
@@ -528,30 +885,18 @@ public class UpdatePartyPacket
get;
set;
}
}
// UPDATE_USER_PARTY
[ProtoContract]
public class UpdateUserPartyPacket
{
[ProtoMember(1)]
public int PartyId
{
get;
set;
}
[ProtoMember(2)]
[ProtoMember(4)]
public int PlayerId
{
get;
set;
}
[ProtoMember(3)]
public UserPartyUpdateType Type
[ProtoMember(5)]
public string PartyName
{
get;
set;
}
} // CREATE일 때 사용
}

View File

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

View File

@@ -1,7 +1,9 @@
using Microsoft.Extensions.Configuration;
using MMOserver.Game;
using MMOserver.Config;
using MMOserver.Game.Service;
using MMOserver.RDB;
using Serilog;
using ServerLib.Utils;
namespace MMOserver;
@@ -9,6 +11,9 @@ class Program
{
private static async Task Main()
{
// 크래시 덤프 핸들러 (Release: .log + .dmp / Debug: .log)
CrashDumpHandler.Register();
// .MinimumLevel.Warning() // Warning 이상만 출력 배포시
IConfigurationRoot config = new ConfigurationBuilder()
@@ -17,6 +22,8 @@ class Program
.AddEnvironmentVariables() // 도커 배포용
.Build();
AppConfig.Initialize(config);
// DB 연결
// DbConnectionFactory dbFactory = new DbConnectionFactory(config);
@@ -30,7 +37,7 @@ class Program
Log.Information("Write Log Started");
int port = 9500;
int port = AppConfig.Server.Port;
string connectionString = "test";
GameServer gameServer = new GameServer(port, connectionString);

View File

@@ -5,6 +5,9 @@ using ServerLib.RDB.Database;
namespace MMOserver.RDB;
/*
* DB Helper 사용 테스트 코드이다.
*/
public class DbConnectionFactory : IDbConnectionFactory
{
private readonly string connectionString;

View File

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

View File

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

View File

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

596
MMOTestServer/README.md Normal file
View File

@@ -0,0 +1,596 @@
# A301 MMO Game Server - 프로젝트 보고서
---
## 1. 프로젝트 개요
| 항목 | 내용 |
|------|------|
| 프로젝트명 | A301 MMO Game Server |
| 언어 | C# (.NET 9.0) |
| 네트워크 | LiteNetLib (UDP 기반) |
| 직렬화 | Protocol Buffers (protobuf-net) |
| 데이터베이스 | MySQL (Dapper ORM) |
| 로깅 | Serilog |
| 배포 | Docker Compose |
---
## 2. 프로젝트 구현 구성
### 2.1 디렉토리 구조
```
a301_mmo_game_server/
├── MMOTestServer/
│ ├── MMOserver/ # 게임 서버 실행 프로젝트
│ │ ├── Api/
│ │ │ └── RestApi.cs # JWT 토큰 검증 (외부 API 호출)
│ │ ├── Game/
│ │ │ ├── GameServer.cs # 메인 게임 서버 (ServerBase 상속)
│ │ │ ├── Player.cs # 플레이어 엔티티 (상태 + 위치)
│ │ │ ├── Channel/
│ │ │ │ ├── Channel.cs # 단일 게임 채널
│ │ │ │ ├── ChannelManager.cs # 채널 관리 (Singleton)
│ │ │ │ └── Maps/
│ │ │ │ └── Robby.cs # 로비 맵
│ │ │ └── Engine/
│ │ │ └── Vector3.cs # 3D 위치 구조체
│ │ ├── Packet/
│ │ │ ├── PacketHeader.cs # PacketCode Enum 정의
│ │ │ └── PacketBody.cs # 모든 패킷 클래스 (ProtoContract)
│ │ ├── RDB/ # 데이터베이스 계층
│ │ │ ├── DbConnectionFactory.cs
│ │ │ ├── Models/
│ │ │ ├── Repositories/
│ │ │ ├── Services/
│ │ │ └── Handlers/
│ │ ├── Utils/
│ │ │ ├── Singleton.cs
│ │ │ └── UuidGeneratorManager.cs
│ │ ├── Program.cs # 서버 진입점
│ │ └── config.json # DB 접속 설정
│ │
│ ├── ServerLib/ # 핵심 네트워크 라이브러리 (DLL)
│ │ ├── Service/
│ │ │ ├── ServerBase.cs # 추상 서버 베이스 클래스
│ │ │ ├── Session.cs # 세션 상태 관리
│ │ │ └── SessionManager.cs # 세션 매니저
│ │ ├── Packet/
│ │ │ ├── PacketSerializer.cs # Protobuf 직렬화 (4바이트 헤더)
│ │ │ └── PacketType.cs # 기본 패킷 타입
│ │ ├── RDB/
│ │ │ ├── Database/
│ │ │ │ └── IDbConnectionFactory.cs
│ │ │ ├── Repositories/
│ │ │ │ └── ARepository.cs # 제네릭 비동기 Repository 베이스
│ │ │ └── Handlers/
│ │ │ ├── HelperHandler.cs
│ │ │ └── Response.cs
│ │ └── Utils/
│ │ └── CrashDumpHandler.cs # 크래시 덤프 핸들러
│ │
│ └── MMOserver.sln
├── ClientTester/ # 클라이언트 테스트 도구
│ └── EchoClientTester/
│ ├── DummyService/ # 더미 플레이어 시뮬레이션
│ │ ├── DummyClientService.cs
│ │ ├── DummyClients.cs
│ │ └── MapBounds.cs
│ ├── EchoDummyService/ # Echo/Ping 테스트
│ │ ├── EchoDummyClientService.cs
│ │ └── EchoDummyClients.cs
│ └── Packet/
├── compose.yaml # Docker Compose (MySQL + Server)
└── ReadMe.md # DB 아키텍처 문서
```
### 2.2 핵심 모듈 구성
#### ServerLib (네트워크 코어 라이브러리)
| 모듈 | 파일 | 역할 |
|------|------|------|
| ServerBase | `ServerBase.cs` | 추상 서버 - 연결/해제/패킷 수신 이벤트 처리 |
| Session | `Session.cs` | 인증 상태 + Peer 매핑 (hashKey, token) |
| PacketSerializer | `PacketSerializer.cs` | 4바이트 헤더(type 2B + size 2B) + Protobuf 페이로드 |
| ARepository | `ARepository.cs` | 제네릭 비동기 CRUD (Dapper.Contrib 기반) |
| CrashDumpHandler | `CrashDumpHandler.cs` | 예외 로깅 + 메모리 힙 덤프 생성 |
#### MMOserver (게임 로직)
| 모듈 | 파일 | 역할 |
|------|------|------|
| GameServer | `GameServer.cs` | 패킷 라우팅 + 게임 로직 처리 (ServerBase 상속) |
| Player | `Player.cs` | 플레이어 데이터 (위치, HP/MP, 닉네임 등) |
| Channel | `Channel.cs` | 채널 단위 플레이어 그룹 관리 |
| ChannelManager | `ChannelManager.cs` | 전역 채널 관리 (Singleton) |
| RestApi | `RestApi.cs` | JWT 토큰 검증 (외부 인증 API 연동) |
| UuidGeneratorManager | `UuidGeneratorManager.cs` | Lock-free 고유 ID 생성기 |
### 2.3 패킷 프로토콜 정의
| 코드 | 패킷명 | 전송 방식 | 설명 |
|------|--------|-----------|------|
| 1 | `ACC_TOKEN` | Reliable | 실제 JWT 토큰 인증 |
| 1001 | `DUMMY_ACC_TOKEN` | Reliable | 더미 클라이언트 인증 |
| 1000 | `ECHO` | Reliable | 네트워크 테스트 (Ping) |
| 2 | `LOAD_CHANNEL` | Reliable | 채널 목록 응답 |
| 3 | `INTO_CHANNEL` | Reliable | 채널 입장 |
| 5 | `UPDATE_CHANNEL_USER` | Reliable | 유저 입장/퇴장 알림 |
| 6 | `TRANSFORM_PLAYER` | **Unreliable** | 이동/회전 동기화 |
| 7 | `ACTION_PLAYER` | Reliable | 공격/스킬/회피 액션 |
| 8 | `STATE_PLAYER` | Reliable | HP/MP 상태 동기화 |
### 2.4 데이터베이스 계층 (RDB)
**아키텍처 패턴**: `Handler → Service → Repository → DB`
```
[Handler] API 요청 수신 / JSON 응답 반환
[Service] 비즈니스 로직 (검증, 변환)
[Repository] 데이터 접근 (Dapper CRUD)
[MySQL] 커넥션 풀 (Min: 5, Max: 100)
```
### 2.5 스레드 모델
| 구분 | 방식 | 설명 |
|------|------|------|
| 네트워크 루프 | **싱글 스레드** | `netManager.PollEvents()` 1ms 주기 호출 |
| 패킷 처리 | 동기 처리 | Poll 루프 내에서 순차적 처리 |
| JWT 검증 | async/await | `HttpClient` 비동기 호출 |
| DB 연산 | async/await | Dapper 비동기 쿼리 |
| UUID 생성 | lock 기반 | 스레드 안전 ID 할당 |
---
## 3. 파이프라인
### 3.1 클라이언트 접속 ~ 게임 플레이 전체 흐름
```
[1] 클라이언트 접속 (UDP)
├─ LiteNetLib ConnectionRequest
│ └─ ServerBase.OnConnectionRequest() → 연결 키 검증
[2] 인증 (Authentication)
├─ 클라이언트 → 서버: ACC_TOKEN 또는 DUMMY_ACC_TOKEN 패킷 전송
├─ [실제 인증] JWT 토큰 → RestApi.VerifyTokenAsync()
│ └─ POST https://a301.api.tolelom.xyz/api/auth/verify
│ ├─ 성공 → username 반환, hashKey 생성
│ ├─ 401 → 즉시 실패 (토큰 무효)
│ └─ 기타 오류 → 3회 재시도 (1초 간격)
├─ [더미 인증] hashKey 직접 수신 (≤1000 범위)
├─ Session 객체 생성 (hashKey, token, peer)
│ └─ peer.Tag에 Session 저장
[3] 채널 선택
├─ 서버 → 클라이언트: LOAD_CHANNEL (채널 목록)
├─ 클라이언트 → 서버: INTO_CHANNEL (채널 선택)
├─ 서버 처리:
│ ├─ 채널에 플레이어 추가
│ ├─ 기존 플레이어 목록 조회
│ └─ 서버 → 클라이언트: INTO_CHANNEL 응답 (기존 플레이어 리스트)
├─ 서버 → 채널 전체: UPDATE_CHANNEL_USER (새 플레이어 입장 알림)
[4] 게임 루프 (실시간 동기화)
├─ TRANSFORM_PLAYER [Unreliable]
│ └─ 위치(X,Y,Z) + 회전(RotY) → 채널 내 브로드캐스트
├─ ACTION_PLAYER [ReliableOrdered]
│ └─ 공격/스킬/회피 → 채널 내 브로드캐스트
├─ STATE_PLAYER [ReliableOrdered]
│ └─ HP/MP 상태 변경 → 채널 내 브로드캐스트
[5] 연결 종료
├─ 클라이언트 → 서버: EXIT_CHANNEL
├─ 서버: 채널에서 플레이어 제거
├─ 서버 → 채널 전체: UPDATE_CHANNEL_USER (퇴장 알림)
└─ 세션 정리 및 Peer 해제
```
### 3.2 패킷 처리 파이프라인
```
수신 (OnNetworkReceive)
┌─────────────────────────────────────┐
│ 4바이트 헤더 파싱 │
│ ├─ type: ushort (2B) → 패킷 종류 │
│ └─ size: ushort (2B) → 페이로드 크기 │
└─────────────────────────────────────┘
┌─────────────────────────────────────┐
│ Protobuf 역직렬화 │
│ └─ byte[] → 패킷 객체 │
└─────────────────────────────────────┘
┌─────────────────────────────────────┐
│ 타입별 분기 │
│ ├─ ECHO (1000) → HandleEcho() │
│ ├─ AUTH (1/1001) → HandleAuth() │
│ └─ GAME (2~8) → HandlePacket() │
└─────────────────────────────────────┘
┌─────────────────────────────────────┐
│ 게임 로직 처리 │
│ └─ 채널 내 브로드캐스트 │
└─────────────────────────────────────┘
송신 (SendTo / BroadcastToChannel)
```
### 3.3 세션 관리 파이프라인
```
PendingPeers (미인증) Sessions (인증 완료)
Dictionary<int, NetPeer> Dictionary<long, NetPeer>
접속 시 등록 ──────────────→ 인증 성공 시 이동
(peerId 기반) (hashKey 기반)
TokenHash (토큰 매핑)
Dictionary<string, long>
token → hashKey 조회
```
- **재접속 처리**: 동일 hashKey로 재접속 시 기존 Peer 강제 해제 → 새 Peer로 교체
- **채널 유지**: 재접속 시 기존 채널 멤버십 유지 (채널 선택 스킵)
### 3.4 빌드 및 배포 파이프라인
```
소스 코드
dotnet build (MMOserver.sln)
├─ ServerLib.csproj → ServerLib.dll
└─ MMOserver.csproj → MMOserver.exe
Docker Build (Dockerfile)
Docker Compose (compose.yaml)
├─ MySQL 컨테이너
└─ MMOServer 컨테이너
└─ UDP 포트: 9050, 9500
```
---
## 4. 버그 및 잠재적 이슈
> 코드 정적 분석을 통해 발견된 버그 및 잠재적 문제점 목록입니다.
### 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] 이동 패킷 재전송 문제
- **문제**: 이동(Transform) 패킷이 `ReliableOrdered`로 전송되어 패킷 손실 시 재전송 발생 → 위치 동기화 지연, Head-of-Line 블로킹
- **해결**: 이동 패킷을 `Unreliable` 전송으로 변경 (`commit: 42f0ef1`)
- **효과**: 실시간성 향상, 네트워크 지연 최소화 (오래된 위치 데이터는 폐기)
#### [P2] 로그인 인증 실패 시 재시도 부재
- **문제**: JWT 토큰 검증 API 호출이 일시적 네트워크 오류로 실패 시 즉시 인증 실패 처리
- **해결**: 3회 재시도 로직 추가 (1초 간격), 401 응답은 즉시 실패 (`commit: c8ce36a`)
- **효과**: 일시적 API 장애에 대한 내결함성 확보
#### [P3] 토큰 → HashKey 매핑 구조
- **문제**: 토큰과 hashKey 간의 매핑이 명확하지 않아 재접속/중복 접속 처리 어려움
- **해결**: `TokenHash` 딕셔너리 도입, 토큰 관리 로직 구조화 (`commit: bfa3394`)
- **효과**: 동일 토큰 재접속 시 기존 세션 정리 및 hashKey 재활용
#### [P4] 에코 클라이언트 수신 버그
- **문제**: 에코 테스트 클라이언트에서 수신 패킷 처리 오류
- **해결**: 수신 로직 버그 수정 (`commit: 18fd8a0`)
#### [P5] 서버 크래시 시 디버깅 정보 부족
- **문제**: 서버 비정상 종료 시 원인 파악 불가
- **해결**: `CrashDumpHandler` 구현 (`commit: 2be1302`)
- Debug 빌드: `.log` 파일 (스택 트레이스)
- Release 빌드: `.log` + `.dmp` 파일 (힙 덤프)
- UnhandledException, UnobservedTaskException 모두 캡처
- **효과**: 프로덕션 환경 크래시 사후 분석 가능
#### [P6] 패킷 레이트 리미팅 부재
- **문제**: 클라이언트의 패킷 전송 빈도 제한 없음 → 패킷 플러딩 공격에 취약
- **해결**: `Session` 클래스에 슬라이딩 윈도우 방식 레이트 리미터 구현
- 초당 최대 120 패킷 허용 (`MaxPacketsPerSecond`)
- 초과 시 해당 패킷 드롭 + 경고 로그
- 3회 연속 초과 시 강제 연결 해제
- `ServerBase.OnNetworkReceive()`에서 인증된 패킷 처리 전 체크
- **적용 파일**: `Session.cs`, `ServerBase.cs`
- **효과**: 악의적 패킷 플러딩 방어, 서버 안정성 향상
#### [P7] 부하 테스트 도구 부재
- **문제**: 대규모 동시접속 시나리오 검증 도구 없음, 기존 더미 클라이언트는 10명 고정
- **해결**: `StressTest` 모듈 신규 구현 (`ClientTester/EchoClientTester/StressTest/`)
- `StressTestClient.cs`: 이동 + Echo RTT 동시 측정 클라이언트
- `StressTestService.cs`: 점진적 Ramp-up, 퍼센타일 레이턴시(P50/P95/P99), CSV 내보내기
- `Program.cs`: CLI 인자 지원 (`stress -c 100 -d 60 --ip ...`) + 대화형 모드 3번 메뉴
- **효과**: N명 동시접속 시나리오 자동 검증, 성능 병목 지점 파악
### 6.2 현재 남아 있는 문제
#### [I1] 서버 사이드 위치 검증 미구현
- **현상**: 클라이언트가 전송하는 위치를 서버에서 검증하지 않음
- **영향**: 스피드핵, 텔레포트 등 치트 방어 불가
- **권장**: `MapBounds` 로직을 서버 사이드에 적용, 비정상 이동 감지 시 보정
#### [I2] 플레이어 데이터 DB 연동 미완성
- **현상**: 플레이어 데이터가 하드코딩된 기본값 사용 (GameServer.cs 내 TODO 주석 존재)
- **영향**: 캐릭터 정보 저장/불러오기 불가, 레벨·닉네임·HP/MP 등 지속성 없음
- **권장**: Player 모델 DB 테이블 생성, 로그인 시 DB 조회
#### [I3] NPC / 파티 시스템 미구현
- **현상**: 패킷 코드(`TRANSFORM_NPC`, `ACTION_NPC`, `UPDATE_PARTY` 등)는 정의되어 있으나 핸들러 없음
- **영향**: 수신 시 경고 로그만 출력되고 무시됨
- **권장**: NPC AI 시스템, 파티 매칭 로직 순차 구현
---
## 7. 정리
### 7.1 아키텍처 요약
```
┌──────────────────────────────────────────────────────┐
│ 클라이언트 (Unity) │
└──────────────┬───────────────────────────┬────────────┘
│ UDP (LiteNetLib) │
┌──────────────▼───────────────────────────▼────────────┐
│ ServerBase (네트워크 코어) │
│ ┌────────────┐ ┌────────────┐ ┌─────────────────┐ │
│ │ 연결 관리 │ │ 패킷 직렬화 │ │ 세션 관리 │ │
│ └────────────┘ └────────────┘ └─────────────────┘ │
└──────────────┬───────────────────────────┬────────────┘
│ │
┌──────────────▼───────────────┐ ┌────────▼────────────┐
│ GameServer (게임 로직) │ │ RestApi (인증) │
│ ┌─────────┐ ┌────────────┐ │ │ JWT 토큰 검증 │
│ │ Channel │ │ Player │ │ │ (외부 API 호출) │
│ │ Manager │ │ State │ │ └─────────────────────┘
│ └─────────┘ └────────────┘ │
└──────────────┬───────────────┘
┌──────────────▼───────────────┐
│ RDB Layer (데이터베이스) │
│ Handler → Service → Repo │
│ → MySQL │
└──────────────────────────────┘
```
### 7.2 기술적 강점
| 항목 | 내용 |
|------|------|
| UDP 기반 통신 | LiteNetLib으로 TCP 오버헤드 없이 실시간 통신 |
| Protobuf 직렬화 | 컴팩트 바이너리 인코딩으로 대역폭 절약 |
| 이동 패킷 Unreliable | HOL 블로킹 방지, 최신 위치만 유효 |
| 싱글 스레드 이벤트 루프 | Lock 불필요, 동시성 이슈 최소화 |
| 비동기 DB/API | async/await로 네트워크 루프 블로킹 방지 |
| 크래시 덤프 | 프로덕션 환경 사후 분석 지원 |
| 계층화된 DB 구조 | Handler-Service-Repository 패턴 |
| Docker 배포 | 컨테이너화된 일관된 배포 환경 |
### 7.3 향후 작업 (Roadmap)
| 우선순위 | 작업 | 설명 |
|---------|------|------|
| **높음** | 플레이어 DB 연동 | 캐릭터 정보 저장/불러오기 완성 (I2) |
| **높음** | 버그 수정 | B2 스레드 안전성, B4 메모리 누수, B6 Echo 레이트 리미팅 |
| **높음** | 서버 사이드 위치 검증 | 치트 방어를 위한 이동 유효성 검사 (I1) |
| **중간** | NPC 시스템 | AI 기반 NPC 이동/전투 로직 (I3) |
| **중간** | 성능 최적화 | ~~O1 브로드캐스트 최적화 (완료)~~, O2 객체 풀링, O4 레이트 리미터 개선 |
| **낮음** | 파티 시스템 | 파티 생성/참여/매칭 (I3) |
| **낮음** | 모니터링 대시보드 | 서버 상태/접속자 수 실시간 모니터링 |
> **완료된 항목**: 패킷 레이트 리미팅 (적용 완료), 부하 테스트 도구 (구현 완료), 크래시 덤프 (적용 완료), O1 브로드캐스트 최적화 (적용 완료)
### 7.4 부하 테스트 도구 (StressTest)
`ClientTester/EchoClientTester/StressTest/` 에 구현됨.
#### 구성 파일
| 파일 | 역할 |
|------|------|
| `StressTestClient.cs` | 개별 스트레스 클라이언트 (이동 + Echo RTT 동시 측정) |
| `StressTestService.cs` | 테스트 오케스트레이터 (Ramp-up, 통계, CSV 내보내기) |
#### 기능
| 기능 | 설명 |
|------|------|
| 점진적 Ramp-up | N초 간격으로 클라이언트 추가 (서버 부하 단계적 증가) |
| 지속시간 제한 | 테스트 자동 종료 (초 단위, 0 = 무제한) |
| 실시간 통계 | 10초마다 접속수, 전송/수신 rate, AvgRTT 출력 |
| 퍼센타일 레이턴시 | P50, P95, P99, Min, Max, Avg RTT 계산 |
| 최악 클라이언트 분석 | RTT 상위 5명 상세 리포트 |
| CSV 내보내기 | `results/stress_{N}clients_{timestamp}.csv` 자동 저장 |
#### 사용법
**CLI 모드:**
```bash
# 기본 (50명, 60초)
dotnet run -- stress
# 커스텀
dotnet run -- stress -c 100 -d 120 --ip 192.168.0.10 --port 9500
# 전체 옵션
dotnet run -- stress \
-c 200 # 클라이언트 수
-d 60 # 테스트 시간 (초, 0=무제한)
-i 100 # 전송 주기 (ms)
-r 1000 # Ramp-up 간격 (ms)
-b 20 # Ramp-up 당 추가 수
--ip localhost # 서버 IP
--port 9500 # 서버 포트
```
**대화형 모드:**
```
메뉴에서 3번 선택 → 클라이언트 수, 테스트 시간 입력
```
#### 출력 예시
```
╔═══════════════════════════════════════════════╗
║ STRESS TEST 최종 리포트 ║
╠═══════════════════════════════════════════════╣
║ 테스트 시간 : 60.0초
║ 클라이언트 : 98/100 접속 유지
╠═══════════════════════════════════════════════╣
║ [처리량]
║ 총 전송 : 118,200 패킷
║ 총 수신 : 117,850 패킷
║ 처리량 : 1,970.0 패킷/초
╠═══════════════════════════════════════════════╣
║ [레이턴시] (RTT 샘플: 59,100개)
║ Min : 0.15 ms
║ Avg : 1.23 ms
║ P50 : 0.89 ms
║ P95 : 3.45 ms
║ P99 : 8.12 ms
║ Max : 25.67 ms
╚═══════════════════════════════════════════════╝
```
### 7.5 최근 개발 이력
| 커밋 | 내용 |
|------|------|
| `85c3276` | 세션 끊길 때 같은 채널에 퇴장 메시지 전송 |
| `c27e846` | 채널 버그 수정 |
| `d4c5a70` | 채널 버그 수정 |
| `ea3f64a` | 스트레스 테스트 기능 추가 / 패킷 처리량 제한 / 프로젝트 상황 README 추가 |
| `2be1302` | 크래시 덤프 기능 추가 (Release: 힙 덤프) |
| `42f0ef1` | 이동 패킷 Unreliable 전송으로 변경 |
| `bfa3394` | 토큰 → HashKey 생성 로직 구조 변경 |
| `c8ce36a` | 로그인 실패 시 재시도 로직 추가 |
| `18fd8a0` | 에코 클라이언트 수신 버그 수정 |
---
> **작성일**: 2026-03-06
> **프로젝트 상태**: 핵심 네트워크 인프라 완성, 게임 콘텐츠 확장 단계
>
> **구현 완료**: 네트워크 코어, 세션 관리, 채널 시스템, 인증, 레이트 리미팅, 크래시 덤프, 부하 테스트 도구
> **미구현**: 플레이어 DB 연동, NPC/파티 시스템, 서버 사이드 위치 검증, 전투/아이템 시스템
> **알려진 버그**: B1 Vector3 타입 불일치, B2 ChannelManager 스레드 안전성, B4 TokenHash 메모리 누수, B6 Echo DoS 취약점

View File

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

View File

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

View File

@@ -15,7 +15,7 @@ namespace ServerLib.Service;
///
/// 흐름:
/// OnPeerConnected → 대기 목록 등록
/// OnNetworkReceive → Auth 패킷(type=1)이면 HashKey(8byte long) 읽어 인증
/// OnNetworkReceive → Auth 패킷(type=1)이면 HashKey(4byte int) 읽어 인증
/// → 이미 같은 HashKey 세션 있으면 이전 피어 끊고 재연결 (WiFi→LTE)
/// → 그 외 패킷은 HandlePacket() 으로 전달
/// OnPeerDisconnected → 세션/대기 목록에서 제거
@@ -30,15 +30,21 @@ public abstract class ServerBase : INetEventListener
protected NetManager netManager = null!;
// 인증 전 대기 피어 (peer.Id → NetPeer)
private readonly Dictionary<int, NetPeer> pendingPeers = new();
protected readonly Dictionary<int, NetPeer> pendingPeers = new();
// 인증된 세션 (hashKey → NetPeer) 재연결 조회용
// peer → hashKey 역방향은 peer.Tag as Session 으로 대체
protected readonly Dictionary<long, NetPeer> sessions = new();
protected readonly Dictionary<int, NetPeer> sessions = new();
// Token / HashKey 관리
protected readonly Dictionary<string, int> tokenHash = new();
// 재사용 NetDataWriter (단일 스레드 폴링이므로 안전)
private readonly NetDataWriter cachedWriter = new();
// async 메서드(HandleAuth 등)의 await 이후 공유 자원 접근 보호용
protected readonly object sessionLock = new();
// 핑 로그 출력 여부
public bool PingLogRtt
{
@@ -114,6 +120,8 @@ public abstract class ServerBase : INetEventListener
// 클라이언트가 연결 해제됐을 때 (타임아웃, 명시적 끊기 등)
public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
{
lock (sessionLock)
{
pendingPeers.Remove(peer.Id);
@@ -123,6 +131,12 @@ public abstract class ServerBase : INetEventListener
// (재연결로 이미 교체된 경우엔 건드리지 않음)
if (sessions.TryGetValue(session.HashKey, out NetPeer? current) && current.Id == peer.Id)
{
// 더미 클라 아니면 token관리
if (!string.IsNullOrEmpty(session.Token))
{
tokenHash.Remove(session.Token);
}
sessions.Remove(session.HashKey);
Log.Information("[Server] 세션 해제 HashKey={Key} Reason={Reason}", session.HashKey, disconnectInfo.Reason);
OnSessionDisconnected(peer, session.HashKey, disconnectInfo);
@@ -131,6 +145,7 @@ public abstract class ServerBase : INetEventListener
peer.Tag = null;
}
}
}
// 연결된 피어로부터 데이터 수신 시 핵심 콜백
public void OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channelNumber, DeliveryMethod deliveryMethod)
@@ -149,16 +164,29 @@ public abstract class ServerBase : INetEventListener
}
// 0이라면 에코 서버 테스트용 따로 처리
if (type == 0)
if (type == 1000)
{
HandleEcho(peer, data);
return;
}
// Auth 패킷은 베이스에서 처리 (raw 8-byte long, protobuf 불필요)
if (type == (ushort)PacketType.Auth)
if (type == (ushort)PacketType.ACC_TOKEN)
{
HandleAuth(peer, payload);
_ = HandleAuth(peer, payload).ContinueWith(t =>
{
if (t.IsFaulted)
{
Log.Error(t.Exception, "[Server] HandleAuth 예외 PeerId={Id}", peer.Id);
}
}, TaskContinuationOptions.OnlyOnFaulted);
return;
}
// Auth 이외 패킷 처리
if (type == (ushort)PacketType.DUMMY_ACC_TOKEN)
{
HandleAuthDummy(peer, payload);
return;
}
@@ -170,6 +198,22 @@ public abstract class ServerBase : INetEventListener
return;
}
// 패킷 레이트 리미팅 체크
if (session.CheckRateLimit())
{
// 3회 연속 초과 시 강제 연결 해제
if (session.RateLimitViolations >= 3)
{
Log.Warning("[Server] 레이트 리밋 초과 강제 해제 HashKey={Key} PeerId={Id}", session.HashKey, peer.Id);
peer.Disconnect();
return;
}
// 패킷 드롭
Log.Warning("[Server] 레이트 리밋 초과 ({Count}회) HashKey={Key} PeerId={Id}", session.RateLimitViolations, session.HashKey, peer.Id);
return;
}
HandlePacket(peer, session.HashKey, type, payload);
}
catch (Exception ex)
@@ -197,59 +241,18 @@ public abstract class ServerBase : INetEventListener
if (PingLogRtt)
{
// rtt 시간 출력
// Log.Debug("[Server] latency : {Latency} ", latency);
}
}
// Echo 서버 테스트
protected abstract void HandleEcho(NetPeer peer, byte[] payload);
private void HandleEcho(NetPeer peer, byte[] payload)
{
if (payload.Length < 4)
{
Log.Warning("[Server] Echo 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
return;
}
// Auth 처리 (더미)
protected abstract void HandleAuthDummy(NetPeer peer, byte[] payload);
// 세션에 넣지는 않는다.
NetDataReader reader = new NetDataReader(payload);
short code = reader.GetShort();
short bodyLength = reader.GetShort();
Log.Debug("[Echo] : addr={Addr}, str={Str}", peer.Address, reader.GetString());
// Echo메시지는 순서보장 안함 HOL Blocking 제거
SendTo(peer, payload, DeliveryMethod.ReliableUnordered);
}
// ─── Auth 처리 (내부) ────────────────────────────────────────────────
private void HandleAuth(NetPeer peer, byte[] payload)
{
if (payload.Length < sizeof(long))
{
Log.Warning("[Server] Auth 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
peer.Disconnect();
return;
}
long hashKey = BitConverter.ToInt64(payload, 0);
if (sessions.TryGetValue(hashKey, out NetPeer? existing))
{
// WiFi → LTE 전환 등 재연결: 이전 피어 교체
existing.Tag = null;
sessions.Remove(hashKey);
Log.Information("[Server] 재연결 HashKey={Key} Old={Old} New={New}", hashKey, existing.Id, peer.Id);
existing.Disconnect();
}
peer.Tag = new Session(hashKey, peer);
sessions[hashKey] = peer;
pendingPeers.Remove(peer.Id);
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
OnSessionConnected(peer, hashKey);
}
// ─── 전송 헬퍼 ───────────────────────────────────────────────────────
// Auth 처리
protected abstract Task HandleAuth(NetPeer peer, byte[] payload);
// peer에게 전송
protected void SendTo(NetPeer peer, byte[] data, DeliveryMethod method = DeliveryMethod.ReliableOrdered)
@@ -275,14 +278,12 @@ public abstract class ServerBase : INetEventListener
netManager.SendToAll(cachedWriter, 0, method, exclude);
}
// ─── 서브클래스 구현 ─────────────────────────────────────────────────
// 인증(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 역직렬화
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

@@ -4,12 +4,80 @@ namespace ServerLib.Service;
public class Session
{
public long HashKey { get; init; }
public NetPeer Peer { get; set; }
public string? Token
{
get;
set;
}
public Session(long hashKey, NetPeer peer)
public string? Username
{
get;
set;
}
public int HashKey
{
get;
init;
}
public NetPeer Peer
{
get;
set;
}
// 패킷 레이트 리미팅
private int packetCount;
private long windowStartTicks;
// 초당 허용 패킷 수
public int MaxPacketsPerSecond { get; set; }
// 연속 초과 횟수
public int RateLimitViolations { get; private set; }
// 패킷 수신 시 호출. 초당 제한 초과 시 true 반환.
public bool CheckRateLimit()
{
long now = Environment.TickCount64;
// 1초(1000ms) 윈도우 초과 시 리셋
if (now - windowStartTicks >= 1000)
{
windowStartTicks = now;
packetCount = 0;
}
packetCount++;
if (packetCount > MaxPacketsPerSecond)
{
RateLimitViolations++;
return true; // 제한 초과
}
return false;
}
// 위반 카운트 초기화
public void ResetViolations()
{
RateLimitViolations = 0;
}
// 채널 입장 시각 (플레이타임 계산용)
public DateTime ChannelJoinedAt { get; set; }
public Session(int hashKey, NetPeer peer, int maxPacketsPerSecond = 60)
{
HashKey = hashKey;
Peer = peer;
Token = null;
MaxPacketsPerSecond = maxPacketsPerSecond;
packetCount = 0;
windowStartTicks = Environment.TickCount64;
RateLimitViolations = 0;
}
}

View File

@@ -0,0 +1,141 @@
using System.Runtime.InteropServices;
using System.Text;
using Serilog;
namespace ServerLib.Utils;
/// <summary>
/// 크래시 핸들러 (Windows / Linux 공통)
/// Register() 를 Program.cs 최상단에서 한 번 호출.
///
/// 덤프 생성은 CLR 환경변수로 처리 (스택 언와인드 전에 찍힘):
/// DOTNET_DbgEnableMiniDump=1
/// DOTNET_DbgMiniDumpType=4
/// DOTNET_DbgMiniDumpName=crashes/crash_%p_%t.dmp
///
/// 생성 파일 (crashes/ 폴더):
/// crash_YYYY-MM-DD_HH-mm-ss.log ← 항상 생성
/// crash_%p_%t.dmp ← CLR이 직접 생성 (정확한 크래시 위치)
/// </summary>
public static class CrashDumpHandler
{
private const string CRASH_DIR = "crashes";
private static int registered;
public static void Register()
{
// 중복 등록 방지
if (Interlocked.Exchange(ref registered, 1) != 0)
{
return;
}
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
Log.Information("[CrashDump] 핸들러 등록 완료 (CrashDir={Dir})", Path.GetFullPath(CRASH_DIR));
}
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception? ex = e.ExceptionObject as Exception;
string tag = $"[CrashDump] UnhandledException (IsTerminating={e.IsTerminating})";
WriteCrash(tag, ex);
}
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
{
e.SetObserved(); // 프로세스 종료 방지
string tag = "[CrashDump] UnobservedTaskException";
WriteCrash(tag, e.Exception);
}
private static void WriteCrash(string tag, Exception? ex)
{
try
{
Directory.CreateDirectory(CRASH_DIR);
string timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
string logPath = Path.Combine(CRASH_DIR, $"crash_{timestamp}.log");
WriteCrashLog(logPath, ex);
Log.Fatal("{Tag} → {Log}", tag, logPath);
}
catch (Exception writeEx)
{
Log.Error(writeEx, "[CrashDump] 로그 저장 실패");
}
finally
{
Log.CloseAndFlush();
}
}
private static void WriteCrashLog(string path, Exception? ex)
{
StringBuilder sb = new();
sb.AppendLine("═══════════════════════════════════════════════════");
sb.AppendLine($" CRASH REPORT {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
sb.AppendLine("═══════════════════════════════════════════════════");
sb.AppendLine();
sb.AppendLine("[Environment]");
sb.AppendLine($" OS : {RuntimeInformation.OSDescription}");
sb.AppendLine($" Runtime : {RuntimeInformation.FrameworkDescription}");
sb.AppendLine($" PID : {Environment.ProcessId}");
sb.AppendLine($" WorkDir : {Environment.CurrentDirectory}");
sb.AppendLine($" MachineName: {Environment.MachineName}");
sb.AppendLine();
sb.AppendLine("[Thread]");
sb.AppendLine($" ThreadId : {Environment.CurrentManagedThreadId}");
sb.AppendLine();
sb.AppendLine("[Exception]");
if (ex is null)
{
sb.AppendLine(" (예외 객체 없음)");
}
else
{
AppendException(sb, ex, 0);
}
File.WriteAllText(path, sb.ToString(), Encoding.UTF8);
}
private static void AppendException(StringBuilder sb, Exception ex, int depth)
{
string indent = new(' ', depth * 2);
sb.AppendLine($"{indent} Type : {ex.GetType().FullName}");
sb.AppendLine($"{indent} Message : {ex.Message}");
sb.AppendLine($"{indent} Source : {ex.Source}");
sb.AppendLine();
sb.AppendLine($"{indent} StackTrace:");
if (ex.StackTrace is not null)
{
foreach (string line in ex.StackTrace.Split('\n'))
{
sb.AppendLine($"{indent} {line.TrimEnd()}");
}
}
if (ex is AggregateException agg)
{
foreach (Exception inner in agg.InnerExceptions)
{
sb.AppendLine();
sb.AppendLine($"{indent} [InnerException]");
AppendException(sb, inner, depth + 1);
}
}
else if (ex.InnerException is not null)
{
sb.AppendLine();
sb.AppendLine($"{indent} [InnerException]");
AppendException(sb, ex.InnerException, depth + 1);
}
}
}

View File

@@ -7,4 +7,20 @@
ports:
- "9050:9050/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