14 Commits

Author SHA1 Message Date
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
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
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
15 changed files with 758 additions and 155 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

@@ -144,7 +144,7 @@ public class DummyClients
Position = new Packet.Position Position = new Packet.Position
{ {
X = position.X, X = position.X,
Y = -0.5f, // 높이는 버린다. Y = -11.09f, // 높이는 버린다.
Z = position.Z Z = position.Z
} }
}; };

View File

@@ -114,6 +114,41 @@ public class PlayerInfo
get; get;
set; set;
} }
[ProtoMember(10)]
public int Experience
{
get;
set;
}
[ProtoMember(11)]
public int NextExp
{
get;
set;
}
[ProtoMember(12)]
public float AttackPower
{
get;
set;
}
[ProtoMember(13)]
public float AttackRange
{
get;
set;
}
[ProtoMember(14)]
public float SprintMultiplier
{
get;
set;
}
} }
// ============================================================ // ============================================================
@@ -163,7 +198,7 @@ public class LoadGamePacket
} }
[ProtoMember(3)] [ProtoMember(3)]
public int MaplId public int MapId
{ {
get; get;
set; set;
@@ -628,7 +663,9 @@ public enum PartyUpdateType
DELETE, DELETE,
JOIN, JOIN,
LEAVE, LEAVE,
UPDATE UPDATE,
INVITE,
KICK
} }
// REQUEST_PARTY (클라 -> 서버) - CREATE: PartyName 사용 / JOIN·LEAVE·DELETE: PartyId 사용 // REQUEST_PARTY (클라 -> 서버) - CREATE: PartyName 사용 / JOIN·LEAVE·DELETE: PartyId 사용
@@ -709,6 +746,103 @@ public class ChatPacket
set; 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;
}
}
// ============================================================ // ============================================================
// 파티 // 파티

View File

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

View File

@@ -152,7 +152,7 @@ public class StressTestClient
{ {
PlayerId = clientId, PlayerId = clientId,
RotY = rotY, RotY = rotY,
Position = new Packet.Position { X = position.X, Y = -0.5f, Z = position.Z } Position = new Packet.Position { X = position.X, Y = -11.09f, Z = position.Z }
}; };
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.TRANSFORM_PLAYER, pkt); byte[] data = PacketSerializer.Serialize((ushort)PacketCode.TRANSFORM_PLAYER, pkt);
writer.Put(data); writer.Put(data);

View File

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

View File

@@ -59,6 +59,38 @@ public class RestApi : Singleton<RestApi>
return null; 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;
}
private sealed class AuthVerifyResponse private sealed class AuthVerifyResponse
{ {
[JsonPropertyName("username")] [JsonPropertyName("username")]
@@ -69,17 +101,59 @@ public class RestApi : Singleton<RestApi>
} }
} }
public sealed class PlayerProfileResponse
{
[JsonPropertyName("nickname")]
public string Nickname { get; set; } = string.Empty;
[JsonPropertyName("level")]
public int Level { get; set; }
[JsonPropertyName("experience")]
public int Experience { get; set; }
[JsonPropertyName("nextExp")]
public int NextExp { get; set; }
[JsonPropertyName("maxHp")]
public double MaxHp { get; set; }
[JsonPropertyName("maxMp")]
public double MaxMp { get; set; }
[JsonPropertyName("attackPower")]
public double AttackPower { get; set; }
[JsonPropertyName("attackRange")]
public double AttackRange { get; set; }
[JsonPropertyName("sprintMultiplier")]
public double SprintMultiplier { get; set; }
[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; }
}
// 레이드 채널 접속 여부 체크 // 레이드 채널 접속 여부 체크
// 성공 시 BossRaidResult 반환, 실패/거절 시 null 반환 // 성공 시 BossRaidResult 반환, 실패/거절 시 null 반환
public async Task<BossRaidResult?> BossRaidAccessAsync(List<string> userNames, int bossId) public async Task<BossRaidResult?> BossRaidAccessAsync(List<string> userNames, int bossId)
{ {
string url = AppConfig.RestApi.BaseUrl + "/api/internal/bossraid/entry"; string url = AppConfig.RestApi.BaseUrl + AppConfig.RestApi.BossRaidAccess;
for (int attempt = 1; attempt <= MAX_RETRY; attempt++) for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
{ {
try try
{ {
HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, new { usernames = userNames, bossId }); HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, new { usernames = userNames, bossId = bossId });
// 401: API 키 인증 실패 // 401: API 키 인증 실패
if (response.StatusCode == HttpStatusCode.Unauthorized) if (response.StatusCode == HttpStatusCode.Unauthorized)
@@ -88,9 +162,10 @@ public class RestApi : Singleton<RestApi>
return null; return null;
} }
// 400: 입장 조건 미충족 / 409: 이미 레이드 중 // 400: 입장 조건 미충족 / 409: 이미 레이드 중 / 503: 이용 가능한 방 없음
if (response.StatusCode == HttpStatusCode.BadRequest || if (response.StatusCode == HttpStatusCode.BadRequest ||
response.StatusCode == HttpStatusCode.Conflict) response.StatusCode == HttpStatusCode.Conflict ||
response.StatusCode == HttpStatusCode.ServiceUnavailable)
{ {
Log.Warning("[RestApi] 보스 레이드 입장 거절 ({Status}) BossId={BossId}", Log.Warning("[RestApi] 보스 레이드 입장 거절 ({Status}) BossId={BossId}",
(int)response.StatusCode, bossId); (int)response.StatusCode, bossId);
@@ -130,6 +205,39 @@ public class RestApi : Singleton<RestApi>
return null; 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);
var body = new Dictionary<string, object?>();
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 BossRaidAccessResponse private sealed class BossRaidAccessResponse
{ {
[JsonPropertyName("roomId")] [JsonPropertyName("roomId")]
@@ -172,6 +280,6 @@ public class RestApi : Singleton<RestApi>
{ {
get; get;
set; set;
} } = new();
} }
} }

View File

@@ -30,9 +30,15 @@ public sealed class ServerConfig
get; get;
} }
public int ChannelCount
{
get;
}
public ServerConfig(IConfigurationSection section) public ServerConfig(IConfigurationSection section)
{ {
Port = int.Parse(section["Port"] ?? throw new InvalidOperationException("Server:Port is required in config.json")); Port = int.Parse(section["Port"] ?? throw new InvalidOperationException("Server:Port is required in config.json"));
ChannelCount = int.Parse(section["ChannelCount"] ?? "1");
} }
} }
@@ -48,6 +54,11 @@ public sealed class RestApiConfig
get; get;
} }
public string BossRaidAccess
{
get;
}
public string ApiKey public string ApiKey
{ {
get; get;
@@ -57,6 +68,7 @@ public sealed class RestApiConfig
{ {
BaseUrl = section["BaseUrl"] ?? throw new InvalidOperationException("RestApi:BaseUrl is required in config.json"); 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"); 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"); ApiKey = section["ApiKey"] ?? throw new InvalidOperationException("RestApi:ApiKey is required in config.json");
} }
} }

View File

@@ -137,6 +137,13 @@ public class Channel
return player; return player;
} }
// 특정 유저의 NetPeer 반환
public NetPeer? GetPeer(int userId)
{
connectPeers.TryGetValue(userId, out NetPeer? peer);
return peer;
}
public int HasUser(int userId) public int HasUser(int userId)
{ {
if (connectUsers.ContainsKey(userId)) if (connectUsers.ContainsKey(userId))

View File

@@ -1,4 +1,5 @@
using LiteNetLib; using LiteNetLib;
using MMOserver.Config;
using MMOserver.Utils; using MMOserver.Utils;
namespace MMOserver.Game.Channel; namespace MMOserver.Game.Channel;
@@ -8,16 +9,12 @@ public class ChannelManager : Singleton<ChannelManager>
// 채널 관리 // 채널 관리
private Dictionary<int, Channel> channels = new Dictionary<int, Channel>(); private Dictionary<int, Channel> channels = new Dictionary<int, Channel>();
// 보스 레이드 채널
private readonly int bossChannelStart = 10000;
private readonly int bossChannelSize = 10;
// 채널별 유저 관리 (유저 key, 채널 val) // 채널별 유저 관리 (유저 key, 채널 val)
private Dictionary<int, int> connectUsers = new Dictionary<int, int>(); private Dictionary<int, int> connectUsers = new Dictionary<int, int>();
public ChannelManager() public ChannelManager()
{ {
Initializer(); Initializer(AppConfig.Server.ChannelCount);
} }
public void Initializer(int channelSize = 1) public void Initializer(int channelSize = 1)
@@ -26,13 +23,6 @@ public class ChannelManager : Singleton<ChannelManager>
{ {
channels.Add(i, new Channel(i)); channels.Add(i, new Channel(i));
} }
// 보스 채널 생성
for (int i = 1; i <= bossChannelSize; i++)
{
int bossChannel = i + bossChannelStart;
channels.Add(bossChannel, new Channel(bossChannel));
}
} }
public Channel GetChannel(int channelId) public Channel GetChannel(int channelId)

View File

@@ -117,7 +117,7 @@ public class GameServer : ServerBase
try try
{ {
string username = ""; string? username = "";
int hashKey; int hashKey;
bool isReconnect; bool isReconnect;
@@ -161,7 +161,7 @@ public class GameServer : ServerBase
((Session)peer.Tag).Token = token; ((Session)peer.Tag).Token = token;
if (username.Length > 0) if (username.Length > 0)
{ {
((Session)peer.Tag).UserName = username; ((Session)peer.Tag).Username = username;
} }
sessions[hashKey] = peer; sessions[hashKey] = peer;
@@ -207,6 +207,21 @@ public class GameServer : ServerBase
int channelId = cm.HasUser(hashKey); int channelId = cm.HasUser(hashKey);
Player? player = channelId >= 0 ? cm.GetChannel(channelId).GetPlayer(hashKey) : null; 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)) if (cm.RemoveUser(hashKey))
{ {
Log.Information("[GameServer] 세션 해제 HashKey={Key} Reason={Reason}", hashKey, info.Reason); Log.Information("[GameServer] 세션 해제 HashKey={Key} Reason={Reason}", hashKey, info.Reason);
@@ -216,9 +231,6 @@ public class GameServer : ServerBase
// 파티 자동 탈퇴 // 파티 자동 탈퇴
HandlePartyLeaveOnExit(channelId, hashKey); HandlePartyLeaveOnExit(channelId, hashKey);
// 레이드 맵이었으면 해제 체크
TryReleaseRaidMap(cm.GetChannel(channelId), player.CurrentMapId);
// 같은 채널 유저들에게 나갔다고 알림 // 같은 채널 유저들에게 나갔다고 알림
SendExitChannelPacket(peer, hashKey, channelId, player); SendExitChannelPacket(peer, hashKey, channelId, player);
} }
@@ -439,7 +451,12 @@ public class GameServer : ServerBase
Mp = player.Mp, Mp = player.Mp,
MaxMp = player.MaxMp, MaxMp = player.MaxMp,
Position = new Position { X = player.PosX, Y = player.PosY, Z = player.PosZ }, Position = new Position { X = player.PosX, Y = player.PosY, Z = player.PosZ },
RotY = player.RotY RotY = player.RotY,
Experience = player.Experience,
NextExp = player.NextExp,
AttackPower = player.AttackPower,
AttackRange = player.AttackRange,
SprintMultiplier = player.SprintMultiplier,
}; };
} }
@@ -447,7 +464,7 @@ public class GameServer : ServerBase
// 패킷 핸들러 // 패킷 핸들러
// ============================================================ // ============================================================
private void OnIntoChannel(NetPeer peer, int hashKey, byte[] payload) private async void OnIntoChannel(NetPeer peer, int hashKey, byte[] payload)
{ {
IntoChannelPacket packet = Serializer.Deserialize<IntoChannelPacket>(new ReadOnlyMemory<byte>(payload)); IntoChannelPacket packet = Serializer.Deserialize<IntoChannelPacket>(new ReadOnlyMemory<byte>(payload));
@@ -463,12 +480,6 @@ public class GameServer : ServerBase
// 파티 자동 탈퇴 // 파티 자동 탈퇴
HandlePartyLeaveOnExit(preChannelId, hashKey); HandlePartyLeaveOnExit(preChannelId, hashKey);
// 레이드 맵 해제 체크
if (player != null)
{
TryReleaseRaidMap(cm.GetChannel(preChannelId), player.CurrentMapId);
}
cm.RemoveUser(hashKey); cm.RemoveUser(hashKey);
Log.Debug("[GameServer] EXIT_CHANNEL HashKey={Key} PlayerId={PlayerId}", hashKey, preChannelId); Log.Debug("[GameServer] EXIT_CHANNEL HashKey={Key} PlayerId={PlayerId}", hashKey, preChannelId);
@@ -500,14 +511,57 @@ public class GameServer : ServerBase
return; return;
} }
// TODO: 실제 서비스에서는 DB/세션에서 플레이어 정보 로드 필요 // API 서버에서 플레이어 프로필 로드
Player newPlayer = new() Player newPlayer = new Player
{ {
HashKey = hashKey, HashKey = hashKey,
PlayerId = hashKey, PlayerId = hashKey,
Nickname = ((Session)peer.Tag).UserName 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); cm.AddUser(packet.ChannelId, hashKey, newPlayer, peer);
Log.Debug("[GameServer] INTO_CHANNEL HashKey={Key} ChannelId={ChannelId}", hashKey, packet.ChannelId); Log.Debug("[GameServer] INTO_CHANNEL HashKey={Key} ChannelId={ChannelId}", hashKey, packet.ChannelId);
@@ -685,12 +739,6 @@ public class GameServer : ServerBase
if (channelId >= 0) if (channelId >= 0)
{ {
HandlePartyLeaveOnExit(channelId, hashKey); HandlePartyLeaveOnExit(channelId, hashKey);
// 레이드 맵 해제 체크
if (player != null)
{
TryReleaseRaidMap(cm.GetChannel(channelId), player.CurrentMapId);
}
} }
cm.RemoveUser(hashKey); cm.RemoveUser(hashKey);
@@ -726,9 +774,6 @@ public class GameServer : ServerBase
player.PosZ = packet.Position.Z; player.PosZ = packet.Position.Z;
player.RotY = packet.RotY; player.RotY = packet.RotY;
// PlayerId 강제 교체 (클라이언트 스푸핑 방지)
packet.PlayerId = hashKey;
// 같은 맵 유저들에게 위치/방향 브로드캐스트 (나 제외) // 같은 맵 유저들에게 위치/방향 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.TRANSFORM_PLAYER, packet); byte[] data = PacketSerializer.Serialize((ushort)PacketCode.TRANSFORM_PLAYER, packet);
BroadcastToMap(channelId, player.CurrentMapId, data, peer, DeliveryMethod.Unreliable); BroadcastToMap(channelId, player.CurrentMapId, data, peer, DeliveryMethod.Unreliable);
@@ -751,9 +796,6 @@ public class GameServer : ServerBase
return; return;
} }
// PlayerId 강제 교체 (클라이언트 스푸핑 방지)
packet.PlayerId = hashKey;
// 같은 맵 유저들에게 행동 브로드캐스트 (나 제외) // 같은 맵 유저들에게 행동 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.ACTION_PLAYER, packet); byte[] data = PacketSerializer.Serialize((ushort)PacketCode.ACTION_PLAYER, packet);
BroadcastToMap(channelId, player.CurrentMapId, data, peer); BroadcastToMap(channelId, player.CurrentMapId, data, peer);
@@ -777,15 +819,6 @@ public class GameServer : ServerBase
return; return;
} }
// PlayerId 강제 교체 (클라이언트 스푸핑 방지)
packet.PlayerId = hashKey;
// HP/MP 범위 클램핑 (클라이언트 조작 방지)
if (packet.MaxHp < 0) packet.MaxHp = 0;
if (packet.MaxMp < 0) packet.MaxMp = 0;
packet.Hp = Math.Clamp(packet.Hp, 0, packet.MaxHp);
packet.Mp = Math.Clamp(packet.Mp, 0, packet.MaxMp);
player.Hp = packet.Hp; player.Hp = packet.Hp;
player.MaxHp = packet.MaxHp; player.MaxHp = packet.MaxHp;
player.Mp = packet.Mp; player.Mp = packet.Mp;
@@ -911,6 +944,84 @@ public class GameServer : ServerBase
BroadcastToChannel(channelId, data); // 채널 전체 파티 목록 갱신 BroadcastToChannel(channelId, data); // 채널 전체 파티 목록 갱신
break; 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;
}
} }
} }
@@ -1002,10 +1113,24 @@ public class GameServer : ServerBase
} }
int oldMapId = player.CurrentMapId; int oldMapId = player.CurrentMapId;
int newMapId = packet.MapId;
if (!channel.ChangeMap(hashKey, player, packet.MapId)) // 일단 보스맵에서 로비로 원복할떄 캐싱해둔 걸로 교체
if (newMapId == -1)
{ {
Log.Warning("[GameServer] CHANGE_MAP 유효하지 않은 맵 HashKey={Key} MapId={MapId}", hashKey, packet.MapId); 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; return;
} }
@@ -1016,12 +1141,12 @@ public class GameServer : ServerBase
BroadcastToMap(channelId, oldMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, exitNotify)); BroadcastToMap(channelId, oldMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, exitNotify));
// 새 맵 유저들에게 입장 알림 (본인 제외) // 새 맵 유저들에게 입장 알림 (본인 제외)
ChangeMapPacket enterNotify = new() { MapId = packet.MapId, IsAdd = true, Player = playerInfo }; ChangeMapPacket enterNotify = new() { MapId = newMapId, IsAdd = true, Player = playerInfo };
BroadcastToMap(channelId, packet.MapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, enterNotify), peer); BroadcastToMap(channelId, newMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, enterNotify), peer);
// 본인에게 새 맵 플레이어 목록 전달 // 본인에게 새 맵 플레이어 목록 전달
ChangeMapPacket response = new() { MapId = packet.MapId }; ChangeMapPacket response = new() { MapId = newMapId };
AMap? newMap = channel.GetMap(packet.MapId); AMap? newMap = channel.GetMap(newMapId);
if (newMap != null) if (newMap != null)
{ {
foreach ((int uid, Player p) in newMap.GetUsers()) foreach ((int uid, Player p) in newMap.GetUsers())
@@ -1036,11 +1161,7 @@ public class GameServer : ServerBase
} }
SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response)); SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
Log.Debug("[GameServer] CHANGE_MAP HashKey={Key} OldMap={OldMapId} NewMap={MapId}", hashKey, oldMapId, newMapId);
// 레이드 맵(1001+)에서 나갔고 남은 유저가 0이면 인스턴스 맵 해제
TryReleaseRaidMap(channel, oldMapId);
Log.Debug("[GameServer] CHANGE_MAP HashKey={Key} OldMap={OldMapId} NewMap={MapId}", hashKey, oldMapId, packet.MapId);
} }
private void OnPartyChangeMap(NetPeer peer, int hashKey, byte[] payload) private void OnPartyChangeMap(NetPeer peer, int hashKey, byte[] payload)
@@ -1148,7 +1269,7 @@ public class GameServer : ServerBase
{ {
Log.Warning("[GameServer] INTO_BOSS_RAID 파티 없음 HashKey={Key}", hashKey); Log.Warning("[GameServer] INTO_BOSS_RAID 파티 없음 HashKey={Key}", hashKey);
SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID, SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket { RaidId = packet.RaidId, IsSuccess = false })); new IntoBossRaidPacket { RaidId = packet.RaidId, IsSuccess = false, Reason = "파티에 속해있지 않습니다." }));
return; return;
} }
@@ -1157,7 +1278,7 @@ public class GameServer : ServerBase
{ {
Log.Warning("[GameServer] INTO_BOSS_RAID 파티장 아님 HashKey={Key} LeaderId={LeaderId}", hashKey, party.LeaderId); Log.Warning("[GameServer] INTO_BOSS_RAID 파티장 아님 HashKey={Key} LeaderId={LeaderId}", hashKey, party.LeaderId);
SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID, SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket { RaidId = packet.RaidId, IsSuccess = false })); new IntoBossRaidPacket { RaidId = packet.RaidId, IsSuccess = false, Reason = "파티장만 보스 레이드를 시작할 수 있습니다." }));
return; return;
} }
@@ -1166,12 +1287,10 @@ public class GameServer : ServerBase
foreach (int memberId in party.PartyMemberIds) foreach (int memberId in party.PartyMemberIds)
{ {
Player? memberPlayer = channel.GetPlayer(memberId); Player? memberPlayer = channel.GetPlayer(memberId);
if (memberPlayer == null) if (memberPlayer != null)
{ {
continue; userNames.Add(memberPlayer.Nickname);
} }
userNames.Add(memberPlayer.Nickname);
} }
BossRaidResult? result = await RestApi.Instance.BossRaidAccessAsync(userNames, packet.RaidId); BossRaidResult? result = await RestApi.Instance.BossRaidAccessAsync(userNames, packet.RaidId);
@@ -1184,7 +1303,7 @@ public class GameServer : ServerBase
{ {
SendTo(peer, SendTo(peer,
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID, PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket { RaidId = -1, IsSuccess = false })); new IntoBossRaidPacket { RaidId = -1, IsSuccess = false, Reason = "보스 레이드 방을 배정받지 못했습니다. 잠시 후 다시 시도해주세요." }));
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId} Failed", hashKey, Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId} Failed", hashKey,
party.PartyId, -1); party.PartyId, -1);
@@ -1262,7 +1381,12 @@ public class GameServer : ServerBase
SendTo(memberPeer, SendTo(memberPeer,
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID, PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket new IntoBossRaidPacket
{ RaidId = assignedRaidMapId, IsSuccess = true, Session = result.SessionName, Token = result.Tokens != null && result.Tokens.TryGetValue(memberPlayer.Nickname, out string? memberToken) ? memberToken : null })); {
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, Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId}", hashKey, party.PartyId,
@@ -1304,22 +1428,6 @@ public class GameServer : ServerBase
BroadcastToChannel(channelId, data); BroadcastToChannel(channelId, data);
} }
// 레이드 맵(1001+)에서 유저가 빠졌을 때, 남은 유저가 0이면 인스턴스 맵 해제
private static void TryReleaseRaidMap(Channel.Channel channel, int mapId)
{
if (mapId < 1001)
{
return;
}
AMap? map = channel.GetMap(mapId);
if (map != null && map.GetUsers().Count == 0)
{
channel.RemoveInstanceMap(mapId);
Log.Debug("[GameServer] 레이드 맵 해제 MapId={MapId}", mapId);
}
}
private void SendError(NetPeer peer, ErrorCode code) private void SendError(NetPeer peer, ErrorCode code)
{ {
ErrorPacket err = new() { Code = code }; ErrorPacket err = new() { Code = code };

View File

@@ -50,6 +50,36 @@ public class Player
set; 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) // 위치/방향 (클라이언트 패킷과 동일하게 float)
public float PosX public float PosX
{ {
@@ -88,4 +118,5 @@ public class Player
get; get;
set; set;
} }
} }

View File

@@ -661,7 +661,9 @@ public enum PartyUpdateType
DELETE, DELETE,
JOIN, JOIN,
LEAVE, LEAVE,
UPDATE UPDATE,
INVITE, // 리더가 대상 플레이어에게 초대 전송
KICK // 리더가 파티원을 추방
} }
// REQUEST_PARTY (클라 -> 서버) - CREATE: PartyName 사용 / JOIN·LEAVE·DELETE: PartyId 사용 // REQUEST_PARTY (클라 -> 서버) - CREATE: PartyName 사용 / JOIN·LEAVE·DELETE: PartyId 사용
@@ -688,6 +690,13 @@ public class RequestPartyPacket
get; get;
set; set;
} // CREATE 시 사용 } // CREATE 시 사용
[ProtoMember(4)]
public int TargetPlayerId
{
get;
set;
} // INVITE, KICK 시 사용
} }
// ============================================================ // ============================================================
@@ -818,6 +827,14 @@ public class IntoBossRaidPacket
get; get;
set; set;
} }
// 실패 사유 (서버 -> 클라, IsSuccess == false 시)
[ProtoMember(5)]
public string Reason
{
get;
set;
}
} }
// PARTY_CHANGE_MAP (클라 -> 서버 전용) // PARTY_CHANGE_MAP (클라 -> 서버 전용)

View File

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

View File

@@ -10,18 +10,18 @@ public class Session
set; set;
} }
public string? Username
{
get;
set;
}
public int HashKey public int HashKey
{ {
get; get;
init; init;
} }
public string UserName
{
get;
set;
}
public NetPeer Peer public NetPeer Peer
{ {
get; get;
@@ -67,6 +67,9 @@ public class Session
RateLimitViolations = 0; RateLimitViolations = 0;
} }
// 채널 입장 시각 (플레이타임 계산용)
public DateTime ChannelJoinedAt { get; set; }
public Session(int hashKey, NetPeer peer, int maxPacketsPerSecond = 60) public Session(int hashKey, NetPeer peer, int maxPacketsPerSecond = 60)
{ {
HashKey = hashKey; HashKey = hashKey;