Compare commits
22 Commits
fix/cross-
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5221261d1e | ||
|
|
462f9d98f1 | ||
|
|
530f32420d | ||
|
|
2ebd0120ab | ||
|
|
849105f8ff | ||
|
|
0617e6a194 | ||
|
|
ca5a345c8f | ||
| cfc242f248 | |||
| 0f1ee36794 | |||
| 64855c5a69 | |||
|
|
f77219e9d2 | ||
|
|
4493729519 | ||
|
|
48c9f1031b | ||
| 53eabe2f3d | |||
|
|
9a155fa056 | ||
|
|
1c63b8532f | ||
| f27cee05bb | |||
| f9db0d26ca | |||
|
|
fb76f49ec0 | ||
|
|
f8fa34edbc | ||
| 7f2cd281da | |||
| 46dd92b27d |
182
CLAUDE.md
Normal file
182
CLAUDE.md
Normal 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 핸들러 미구현
|
||||||
|
- 수평 확장 미지원 (단일 서버 인스턴스)
|
||||||
@@ -29,7 +29,7 @@ public class DummyClients
|
|||||||
private float dirZ = 0f;
|
private float dirZ = 0f;
|
||||||
|
|
||||||
// 맵 경계
|
// 맵 경계
|
||||||
public MapBounds Map { get; set; } = new MapBounds(-50f, 50f, -50f, 50f);
|
public MapBounds Map { get; set; } = new MapBounds(-95f, -25f, -30f, 10f);
|
||||||
|
|
||||||
// 통계
|
// 통계
|
||||||
public int SentCount
|
public int SentCount
|
||||||
@@ -86,6 +86,9 @@ public class DummyClients
|
|||||||
|
|
||||||
manager.Start();
|
manager.Start();
|
||||||
manager.Connect(ip, port, key);
|
manager.Connect(ip, port, key);
|
||||||
|
|
||||||
|
position.X = -60;
|
||||||
|
position.Z = 25;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void UpdateDummy()
|
public void UpdateDummy()
|
||||||
@@ -144,7 +147,7 @@ public class DummyClients
|
|||||||
Position = new Packet.Position
|
Position = new Packet.Position
|
||||||
{
|
{
|
||||||
X = position.X,
|
X = position.X,
|
||||||
Y = -0.5f, // 높이는 버린다.
|
Y = -3.7f, // 높이는 버린다.
|
||||||
Z = position.Z
|
Z = position.Z
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
// 파티
|
// 파티
|
||||||
|
|||||||
@@ -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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"ServerIp": "localhost",
|
"ServerIp": "j14a301.p.ssafy.io",
|
||||||
"ServerPort": 9500,
|
"ServerPort": 40001,
|
||||||
"ConnectionKey": "test",
|
"ConnectionKey": "test",
|
||||||
"ClientCount": 80
|
"ClientCount": 80
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,5 +9,5 @@ public sealed class BossRaidResult
|
|||||||
public int BossId { get; init; }
|
public int BossId { get; init; }
|
||||||
public List<string> Players { get; init; } = new();
|
public List<string> Players { get; init; } = new();
|
||||||
public string Status { get; init; } = string.Empty;
|
public string Status { get; init; } = string.Empty;
|
||||||
public string? Tokens { get; init; }
|
public Dictionary<string, string>? Tokens { get; init; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,10 +9,9 @@ namespace MMOserver.Api;
|
|||||||
|
|
||||||
public class RestApi : Singleton<RestApi>
|
public class RestApi : Singleton<RestApi>
|
||||||
{
|
{
|
||||||
private readonly HttpClient httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
|
|
||||||
|
|
||||||
private const int MAX_RETRY = 3;
|
private const int MAX_RETRY = 3;
|
||||||
private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(1);
|
private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(1);
|
||||||
|
private readonly HttpClient httpClient = new() { Timeout = TimeSpan.FromSeconds(5) };
|
||||||
|
|
||||||
public RestApi()
|
public RestApi()
|
||||||
{
|
{
|
||||||
@@ -35,7 +34,7 @@ public class RestApi : Singleton<RestApi>
|
|||||||
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
if (response.StatusCode == HttpStatusCode.Unauthorized)
|
||||||
{
|
{
|
||||||
Log.Warning("[RestApi] 토큰 인증 실패 (401)");
|
Log.Warning("[RestApi] 토큰 인증 실패 (401)");
|
||||||
return "";
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
response.EnsureSuccessStatusCode();
|
response.EnsureSuccessStatusCode();
|
||||||
@@ -56,24 +55,46 @@ public class RestApi : Singleton<RestApi>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return "";
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private sealed class AuthVerifyResponse
|
// 플레이어 프로필 조회 - 성공 시 PlayerProfileResponse 반환
|
||||||
|
public async Task<PlayerProfileResponse?> GetPlayerProfileAsync(string username)
|
||||||
{
|
{
|
||||||
[JsonPropertyName("username")]
|
string url = AppConfig.RestApi.BaseUrl + "/api/internal/player/profile?username=" + Uri.EscapeDataString(username);
|
||||||
public string? Username
|
for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
|
||||||
{
|
{
|
||||||
get;
|
try
|
||||||
set;
|
{
|
||||||
|
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 반환
|
// 성공 시 BossRaidResult 반환, 실패/거절 시 null 반환
|
||||||
public async Task<BossRaidResult?> BossRaidAccesssAsync(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++)
|
||||||
{
|
{
|
||||||
@@ -88,10 +109,13 @@ public class RestApi : Singleton<RestApi>
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 400: 입장 조건 미충족 (레벨 부족, 이미 진행중 등)
|
// 400: 입장 조건 미충족 / 409: 이미 레이드 중 / 503: 이용 가능한 방 없음
|
||||||
if (response.StatusCode == HttpStatusCode.BadRequest)
|
if (response.StatusCode == HttpStatusCode.BadRequest ||
|
||||||
|
response.StatusCode == HttpStatusCode.Conflict ||
|
||||||
|
response.StatusCode == HttpStatusCode.ServiceUnavailable)
|
||||||
{
|
{
|
||||||
Log.Warning("[RestApi] 보스 레이드 입장 거절 (400) BossId={BossId}", bossId);
|
Log.Warning("[RestApi] 보스 레이드 입장 거절 ({Status}) BossId={BossId}",
|
||||||
|
(int)response.StatusCode, bossId);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,6 +152,163 @@ 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);
|
||||||
|
|
||||||
|
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
|
private sealed class BossRaidAccessResponse
|
||||||
{
|
{
|
||||||
[JsonPropertyName("roomId")]
|
[JsonPropertyName("roomId")]
|
||||||
@@ -166,10 +347,10 @@ public class RestApi : Singleton<RestApi>
|
|||||||
}
|
}
|
||||||
|
|
||||||
[JsonPropertyName("tokens")]
|
[JsonPropertyName("tokens")]
|
||||||
public string? Tokens
|
public Dictionary<string, string>? Tokens
|
||||||
{
|
{
|
||||||
get;
|
get;
|
||||||
set;
|
set;
|
||||||
}
|
} = new();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,14 @@ using MMOserver.Game.Party;
|
|||||||
|
|
||||||
namespace MMOserver.Game.Channel;
|
namespace MMOserver.Game.Channel;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Channel 클래스
|
||||||
|
* - 채널 내 Peer 관리
|
||||||
|
* - 채널 내 유저관리
|
||||||
|
* - 맵 관리
|
||||||
|
* - 인스턴스 던전 관리
|
||||||
|
* - 동적 맵 id 생성
|
||||||
|
*/
|
||||||
public class Channel
|
public class Channel
|
||||||
{
|
{
|
||||||
// 채널 내 유저 NetPeer (hashKey → NetPeer) — BroadcastToChannel 교차 조회 제거용
|
// 채널 내 유저 NetPeer (hashKey → NetPeer) — BroadcastToChannel 교차 조회 제거용
|
||||||
@@ -79,11 +87,14 @@ public class Channel
|
|||||||
currentMap.RemoveUser(userId);
|
currentMap.RemoveUser(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
connectUsers.Remove(userId);
|
if (connectUsers.Remove(userId))
|
||||||
connectPeers.Remove(userId);
|
{
|
||||||
UserCount--;
|
UserCount--;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
connectPeers.Remove(userId);
|
||||||
|
}
|
||||||
|
|
||||||
// 맵 이동 (현재 맵 제거 → 새 맵 추가 → CurrentMapId 갱신)
|
// 맵 이동 (현재 맵 제거 → 새 맵 추가 → CurrentMapId 갱신)
|
||||||
public bool ChangeMap(int userId, Player player, int mapId)
|
public bool ChangeMap(int userId, Player player, int mapId)
|
||||||
{
|
{
|
||||||
@@ -134,6 +145,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))
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
namespace MMOserver.Game.Channel.Maps;
|
namespace MMOserver.Game.Channel.Maps;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 게임 맵
|
||||||
|
* - 각 존 관리
|
||||||
|
* - 맵의 유저 관리
|
||||||
|
*/
|
||||||
public abstract class AMap
|
public abstract class AMap
|
||||||
{
|
{
|
||||||
private Dictionary<int, Player> users = new Dictionary<int, Player>();
|
private Dictionary<int, Player> users = new Dictionary<int, Player>();
|
||||||
|
|||||||
@@ -1,8 +1,15 @@
|
|||||||
namespace MMOserver.Game.Channel.Maps;
|
namespace MMOserver.Game.Channel.Maps;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 맵 타입
|
||||||
|
* - ROBBY : 마을
|
||||||
|
* - DUNGEON : 오픈월드 던전 (마을 외곽)
|
||||||
|
* - INSTANCE : 인스턴스 레이드 던전(포톤용)
|
||||||
|
*/
|
||||||
public enum EnumMap : int
|
public enum EnumMap : int
|
||||||
{
|
{
|
||||||
NONE = 0,
|
NONE = 0,
|
||||||
ROBBY = 1,
|
ROBBY = 1,
|
||||||
|
DUNGEON = 2,
|
||||||
INSTANCE = 10,
|
INSTANCE = 10,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ using MMOserver.Game.Engine;
|
|||||||
|
|
||||||
namespace MMOserver.Game.Channel.Maps.InstanceDungeun;
|
namespace MMOserver.Game.Channel.Maps.InstanceDungeun;
|
||||||
|
|
||||||
// 인스턴스 보스 맵에 들어갈때 쓰는 것
|
/*
|
||||||
|
* 인스턴스 보스 레이드에 진입은 하나의 Map으로 처리
|
||||||
|
*/
|
||||||
public class BossInstance : AMap
|
public class BossInstance : AMap
|
||||||
{
|
{
|
||||||
private EnumMap enumMap;
|
private EnumMap enumMap;
|
||||||
|
|||||||
@@ -2,18 +2,14 @@
|
|||||||
|
|
||||||
namespace MMOserver.Game.Channel.Maps;
|
namespace MMOserver.Game.Channel.Maps;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 마을(로비)
|
||||||
|
*/
|
||||||
public class Robby : AMap
|
public class Robby : AMap
|
||||||
{
|
{
|
||||||
private EnumMap enumMap;
|
private EnumMap enumMap;
|
||||||
private int mapId;
|
private int mapId;
|
||||||
|
|
||||||
// 마을 시작 지점 넣어 둔다.
|
|
||||||
public static Vector3 StartPosition
|
|
||||||
{
|
|
||||||
get;
|
|
||||||
set;
|
|
||||||
} = new Vector3(0, 0, 0);
|
|
||||||
|
|
||||||
public Robby(int mapId, EnumMap enumMap = EnumMap.ROBBY)
|
public Robby(int mapId, EnumMap enumMap = EnumMap.ROBBY)
|
||||||
{
|
{
|
||||||
this.enumMap = enumMap;
|
this.enumMap = enumMap;
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -28,6 +28,12 @@ public class PartyManager
|
|||||||
memeberIds = new List<int>();
|
memeberIds = new List<int>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 리더 중복 방지: 기존 멤버 목록에 리더가 없을 때만 추가
|
||||||
|
if (!memeberIds.Contains(leaderId))
|
||||||
|
{
|
||||||
|
memeberIds.Add(leaderId);
|
||||||
|
}
|
||||||
|
|
||||||
party = new PartyInfo
|
party = new PartyInfo
|
||||||
{
|
{
|
||||||
PartyId = partyId,
|
PartyId = partyId,
|
||||||
@@ -35,10 +41,14 @@ public class PartyManager
|
|||||||
PartyName = partyName,
|
PartyName = partyName,
|
||||||
PartyMemberIds = memeberIds
|
PartyMemberIds = memeberIds
|
||||||
};
|
};
|
||||||
party.PartyMemberIds.Add(leaderId);
|
|
||||||
|
|
||||||
parties[partyId] = party;
|
parties[partyId] = party;
|
||||||
playerPartyMap[leaderId] = partyId;
|
|
||||||
|
// 모든 멤버를 playerPartyMap에 등록
|
||||||
|
foreach (int memberId in memeberIds)
|
||||||
|
{
|
||||||
|
playerPartyMap[memberId] = partyId;
|
||||||
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
using MMOserver.Packet;
|
||||||
|
|
||||||
namespace MMOserver.Game;
|
namespace MMOserver.Game;
|
||||||
|
|
||||||
public class Player
|
public class Player
|
||||||
@@ -50,6 +52,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 +120,25 @@ public class Player
|
|||||||
get;
|
get;
|
||||||
set;
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
36
MMOTestServer/MMOserver/Game/Service/ActionPlayerHandler.cs
Normal file
36
MMOTestServer/MMOserver/Game/Service/ActionPlayerHandler.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
86
MMOTestServer/MMOserver/Game/Service/ChangeMapHandler.cs
Normal file
86
MMOTestServer/MMOserver/Game/Service/ChangeMapHandler.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
85
MMOTestServer/MMOserver/Game/Service/ChatHandler.cs
Normal file
85
MMOTestServer/MMOserver/Game/Service/ChatHandler.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
40
MMOTestServer/MMOserver/Game/Service/ExitChannelHandler.cs
Normal file
40
MMOTestServer/MMOserver/Game/Service/ExitChannelHandler.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
491
MMOTestServer/MMOserver/Game/Service/GameServer.cs
Normal file
491
MMOTestServer/MMOserver/Game/Service/GameServer.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
169
MMOTestServer/MMOserver/Game/Service/IntoBossRaidHandler.cs
Normal file
169
MMOTestServer/MMOserver/Game/Service/IntoBossRaidHandler.cs
Normal 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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
159
MMOTestServer/MMOserver/Game/Service/IntoChannelHandle.cs
Normal file
159
MMOTestServer/MMOserver/Game/Service/IntoChannelHandle.cs
Normal 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}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
140
MMOTestServer/MMOserver/Game/Service/IntoChannelPartyHandler.cs
Normal file
140
MMOTestServer/MMOserver/Game/Service/IntoChannelPartyHandler.cs
Normal 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] 파티생성 실패 !!!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
212
MMOTestServer/MMOserver/Game/Service/RequestPartyHandler.cs
Normal file
212
MMOTestServer/MMOserver/Game/Service/RequestPartyHandler.cs
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
42
MMOTestServer/MMOserver/Game/Service/StatePlayerHandler.cs
Normal file
42
MMOTestServer/MMOserver/Game/Service/StatePlayerHandler.cs
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -198,7 +198,7 @@ public class LoadGamePacket
|
|||||||
}
|
}
|
||||||
|
|
||||||
[ProtoMember(3)]
|
[ProtoMember(3)]
|
||||||
public int MaplId
|
public int MapId
|
||||||
{
|
{
|
||||||
get;
|
get;
|
||||||
set;
|
set;
|
||||||
@@ -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 (클라 -> 서버 전용)
|
||||||
|
|||||||
@@ -2,73 +2,73 @@ namespace MMOserver.Packet;
|
|||||||
|
|
||||||
public enum PacketCode : ushort
|
public enum PacketCode : ushort
|
||||||
{
|
{
|
||||||
|
// 초기 클라이언트 시작시 jwt토큰 받아옴
|
||||||
|
ACC_TOKEN = 1,
|
||||||
|
|
||||||
|
// 내 정보 로드 (서버 -> 클라)
|
||||||
|
LOAD_GAME = 2,
|
||||||
|
|
||||||
|
// 모든 채널 로드 - jwt토큰 검증후 게임에 들어갈지 말지 (내 데이터도 전송)
|
||||||
|
// (서버 -> 클라)
|
||||||
|
LOAD_CHANNEL = 3,
|
||||||
|
|
||||||
|
// 나 채널 접속 (클라 -> 서버)
|
||||||
|
INTO_CHANNEL = 4,
|
||||||
|
|
||||||
|
// 파티 채널 접속 (클라 -> 서버)
|
||||||
|
INTO_CHANNEL_PARTY = 5,
|
||||||
|
|
||||||
|
// 새로운 유저 채널 접속 (서버 -> 클라) / 유저 채널 나감 (서버 -> 클라)
|
||||||
|
UPDATE_CHANNEL_USER = 6,
|
||||||
|
|
||||||
|
// 채널 나가기 (클라 -> 서버)
|
||||||
|
EXIT_CHANNEL = 7,
|
||||||
|
|
||||||
|
// 맵 이동
|
||||||
|
CHANGE_MAP = 8,
|
||||||
|
|
||||||
|
// 단체로 맵 이동
|
||||||
|
PARTY_CHANGE_MAP = 9,
|
||||||
|
|
||||||
|
// 파티장이 보스 레이드(인스턴스 던전) 입장 신청 (클라 -> 서버)
|
||||||
|
INTO_BOSS_RAID = 10,
|
||||||
|
|
||||||
|
// 플레이어 위치, 방향 (서버 -> 클라 \ 클라 -> 서버)
|
||||||
|
TRANSFORM_PLAYER = 11,
|
||||||
|
|
||||||
|
// 플레이어 행동 업데이트 (서버 -> 클라 \ 클라 -> 서버)
|
||||||
|
ACTION_PLAYER = 12,
|
||||||
|
|
||||||
|
// 플레이어 스테이트 업데이트 (서버 -> 클라 \ 클라 -> 서버)
|
||||||
|
STATE_PLAYER = 13,
|
||||||
|
|
||||||
|
// NPC 위치, 방향 (서버 -> 클라)
|
||||||
|
TRANSFORM_NPC = 14,
|
||||||
|
|
||||||
|
// NPC 행동 업데이트 (서버 -> 클라)
|
||||||
|
ACTION_NPC = 15,
|
||||||
|
|
||||||
|
// NPC 스테이트 업데이트 (서버 -> 클라)
|
||||||
|
STATE_NPC = 16,
|
||||||
|
|
||||||
|
// 데미지 UI 전달 (서버 -> 클라)
|
||||||
|
DAMAGE = 17,
|
||||||
|
|
||||||
|
// 파티 생성/삭제, 파티원 추가/제거 (서버 -> 클라)
|
||||||
|
UPDATE_PARTY = 18,
|
||||||
|
|
||||||
|
// 파티 참가/탈퇴/생성/해산 요청 (클라 -> 서버)
|
||||||
|
REQUEST_PARTY = 19,
|
||||||
|
|
||||||
|
// 채팅 (클라 -> 서버 & 서버 -> 클라) - GLOBAL / PARTY / WHISPER
|
||||||
|
CHAT = 20,
|
||||||
|
|
||||||
// ECHO
|
// ECHO
|
||||||
ECHO = 1000,
|
ECHO = 1000,
|
||||||
|
|
||||||
// DUMMY 클라는 이걸로 jwt토큰 안받음
|
// DUMMY 클라는 이걸로 jwt토큰 안받음
|
||||||
DUMMY_ACC_TOKEN = 1001,
|
DUMMY_ACC_TOKEN = 1001,
|
||||||
|
|
||||||
// 초기 클라이언트 시작시 jwt토큰 받아옴
|
|
||||||
ACC_TOKEN = 1,
|
|
||||||
|
|
||||||
// 내 정보 로드 (서버 -> 클라)
|
|
||||||
LOAD_GAME,
|
|
||||||
|
|
||||||
// 모든 채널 로드 - jwt토큰 검증후 게임에 들어갈지 말지 (내 데이터도 전송)
|
|
||||||
// (서버 -> 클라)
|
|
||||||
LOAD_CHANNEL,
|
|
||||||
|
|
||||||
// 나 채널 접속 (클라 -> 서버)
|
|
||||||
INTO_CHANNEL,
|
|
||||||
|
|
||||||
// 파티 채널 접속 (클라 -> 서버)
|
|
||||||
INTO_CHANNEL_PARTY,
|
|
||||||
|
|
||||||
// 새로운 유저 채널 접속 (서버 -> 클라) / 유저 채널 나감 (서버 -> 클라)
|
|
||||||
UPDATE_CHANNEL_USER,
|
|
||||||
|
|
||||||
// 채널 나가기 (클라 -> 서버)
|
|
||||||
EXIT_CHANNEL,
|
|
||||||
|
|
||||||
// 맵 이동
|
|
||||||
CHANGE_MAP,
|
|
||||||
|
|
||||||
// 단체로 맵 이동
|
|
||||||
PARTY_CHANGE_MAP,
|
|
||||||
|
|
||||||
// 파티장이 보스 레이드(인스턴스 던전) 입장 신청 (클라 -> 서버)
|
|
||||||
INTO_BOSS_RAID,
|
|
||||||
|
|
||||||
// 플레이어 위치, 방향 (서버 -> 클라 \ 클라 -> 서버)
|
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using MMOserver.Config;
|
using MMOserver.Config;
|
||||||
using MMOserver.Game;
|
using MMOserver.Game.Service;
|
||||||
using MMOserver.RDB;
|
using MMOserver.RDB;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
using ServerLib.Utils;
|
using ServerLib.Utils;
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ using ServerLib.RDB.Database;
|
|||||||
|
|
||||||
namespace MMOserver.RDB;
|
namespace MMOserver.RDB;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* DB Helper 사용 테스트 코드이다.
|
||||||
|
*/
|
||||||
public class DbConnectionFactory : IDbConnectionFactory
|
public class DbConnectionFactory : IDbConnectionFactory
|
||||||
{
|
{
|
||||||
private readonly string connectionString;
|
private readonly string connectionString;
|
||||||
|
|||||||
@@ -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": {
|
||||||
|
|||||||
@@ -42,6 +42,9 @@ public abstract class ServerBase : INetEventListener
|
|||||||
// 재사용 NetDataWriter (단일 스레드 폴링이므로 안전)
|
// 재사용 NetDataWriter (단일 스레드 폴링이므로 안전)
|
||||||
private readonly NetDataWriter cachedWriter = new();
|
private readonly NetDataWriter cachedWriter = new();
|
||||||
|
|
||||||
|
// async 메서드(HandleAuth 등)의 await 이후 공유 자원 접근 보호용
|
||||||
|
protected readonly object sessionLock = new();
|
||||||
|
|
||||||
// 핑 로그 출력 여부
|
// 핑 로그 출력 여부
|
||||||
public bool PingLogRtt
|
public bool PingLogRtt
|
||||||
{
|
{
|
||||||
@@ -117,6 +120,8 @@ public abstract class ServerBase : INetEventListener
|
|||||||
|
|
||||||
// 클라이언트가 연결 해제됐을 때 (타임아웃, 명시적 끊기 등)
|
// 클라이언트가 연결 해제됐을 때 (타임아웃, 명시적 끊기 등)
|
||||||
public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
|
public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
|
||||||
|
{
|
||||||
|
lock (sessionLock)
|
||||||
{
|
{
|
||||||
pendingPeers.Remove(peer.Id);
|
pendingPeers.Remove(peer.Id);
|
||||||
|
|
||||||
@@ -140,6 +145,7 @@ public abstract class ServerBase : INetEventListener
|
|||||||
peer.Tag = null;
|
peer.Tag = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 연결된 피어로부터 데이터 수신 시 핵심 콜백
|
// 연결된 피어로부터 데이터 수신 시 핵심 콜백
|
||||||
public void OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channelNumber, DeliveryMethod deliveryMethod)
|
public void OnNetworkReceive(NetPeer peer, NetPacketReader reader, byte channelNumber, DeliveryMethod deliveryMethod)
|
||||||
@@ -167,10 +173,18 @@ public abstract class ServerBase : INetEventListener
|
|||||||
// Auth 패킷은 베이스에서 처리 (raw 8-byte long, protobuf 불필요)
|
// Auth 패킷은 베이스에서 처리 (raw 8-byte long, protobuf 불필요)
|
||||||
if (type == (ushort)PacketType.ACC_TOKEN)
|
if (type == (ushort)PacketType.ACC_TOKEN)
|
||||||
{
|
{
|
||||||
HandleAuth(peer, payload);
|
_ = HandleAuth(peer, payload).ContinueWith(t =>
|
||||||
|
{
|
||||||
|
if (t.IsFaulted)
|
||||||
|
{
|
||||||
|
Log.Error(t.Exception, "[Server] HandleAuth 예외 PeerId={Id}", peer.Id);
|
||||||
|
}
|
||||||
|
}, TaskContinuationOptions.OnlyOnFaulted);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
else if (type == (ushort)PacketType.DUMMY_ACC_TOKEN)
|
|
||||||
|
// Auth 이외 패킷 처리
|
||||||
|
if (type == (ushort)PacketType.DUMMY_ACC_TOKEN)
|
||||||
{
|
{
|
||||||
HandleAuthDummy(peer, payload);
|
HandleAuthDummy(peer, payload);
|
||||||
return;
|
return;
|
||||||
@@ -195,9 +209,9 @@ public abstract class ServerBase : INetEventListener
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
Log.Warning("[Server] 레이트 리밋 초과 ({Count}회) HashKey={Key} PeerId={Id}", session.RateLimitViolations, session.HashKey,
|
// 패킷 드롭
|
||||||
peer.Id);
|
Log.Warning("[Server] 레이트 리밋 초과 ({Count}회) HashKey={Key} PeerId={Id}", session.RateLimitViolations, session.HashKey, peer.Id);
|
||||||
return; // 패킷 드롭
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
HandlePacket(peer, session.HashKey, type, payload);
|
HandlePacket(peer, session.HashKey, type, payload);
|
||||||
@@ -227,22 +241,18 @@ public abstract class ServerBase : INetEventListener
|
|||||||
if (PingLogRtt)
|
if (PingLogRtt)
|
||||||
{
|
{
|
||||||
// rtt 시간 출력
|
// rtt 시간 출력
|
||||||
|
// Log.Debug("[Server] latency : {Latency} ", latency);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Echo 서버 테스트
|
// Echo 서버 테스트
|
||||||
|
|
||||||
protected abstract void HandleEcho(NetPeer peer, byte[] payload);
|
protected abstract void HandleEcho(NetPeer peer, byte[] payload);
|
||||||
|
|
||||||
// ─── Auth 처리 (더미) ────────────────────────────────────────────────
|
// Auth 처리 (더미)
|
||||||
|
|
||||||
protected abstract void HandleAuthDummy(NetPeer peer, byte[] payload);
|
protected abstract void HandleAuthDummy(NetPeer peer, byte[] payload);
|
||||||
|
|
||||||
// ─── Auth 처리 ────────────────────────────────────────────────
|
// Auth 처리
|
||||||
|
protected abstract Task HandleAuth(NetPeer peer, byte[] payload);
|
||||||
protected abstract void HandleAuth(NetPeer peer, byte[] payload);
|
|
||||||
|
|
||||||
// ─── 전송 헬퍼 ───────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
// peer에게 전송
|
// peer에게 전송
|
||||||
protected void SendTo(NetPeer peer, byte[] data, DeliveryMethod method = DeliveryMethod.ReliableOrdered)
|
protected void SendTo(NetPeer peer, byte[] data, DeliveryMethod method = DeliveryMethod.ReliableOrdered)
|
||||||
@@ -268,8 +278,6 @@ public abstract class ServerBase : INetEventListener
|
|||||||
netManager.SendToAll(cachedWriter, 0, method, exclude);
|
netManager.SendToAll(cachedWriter, 0, method, exclude);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── 서브클래스 구현 ─────────────────────────────────────────────────
|
|
||||||
|
|
||||||
// 인증(Auth) 완료 후 호출
|
// 인증(Auth) 완료 후 호출
|
||||||
protected abstract void OnSessionConnected(NetPeer peer, int hashKey);
|
protected abstract void OnSessionConnected(NetPeer peer, int hashKey);
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|||||||
@@ -36,8 +36,6 @@ public static class CrashDumpHandler
|
|||||||
Log.Information("[CrashDump] 핸들러 등록 완료 (CrashDir={Dir})", Path.GetFullPath(CRASH_DIR));
|
Log.Information("[CrashDump] 핸들러 등록 완료 (CrashDir={Dir})", Path.GetFullPath(CRASH_DIR));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── 핸들러 ──────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
|
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
|
||||||
{
|
{
|
||||||
Exception? ex = e.ExceptionObject as Exception;
|
Exception? ex = e.ExceptionObject as Exception;
|
||||||
@@ -52,8 +50,6 @@ public static class CrashDumpHandler
|
|||||||
WriteCrash(tag, e.Exception);
|
WriteCrash(tag, e.Exception);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── 핵심 처리 ───────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
private static void WriteCrash(string tag, Exception? ex)
|
private static void WriteCrash(string tag, Exception? ex)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|||||||
Reference in New Issue
Block a user