10 Commits

Author SHA1 Message Date
qornwh1
48c9f1031b fix : 서버 버그 수정 작업 머지
Merge branch 'fix/mmo-server-logic-bugs' of https://git.tolelom.xyz/A301/a301_mmo_game_server

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

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 23:26:39 +09:00
qornwh1
9a155fa056 feat : 보스맵 종료후 -> 로비 맵 이동 처리 2026-03-17 14:28:39 +09:00
qornwh1
1c63b8532f fix : 코드 버그 수정 2026-03-17 12:58:04 +09:00
f27cee05bb fix: merge conflict 해결 — BossRaid 토큰 Dictionary 처리 및 개별 전송
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 12:55:25 +09:00
f9db0d26ca fix: BossRaid 토큰 처리 수정 및 merge conflict 해결
- RestApi.cs: Tokens를 Dictionary<string, string>?으로 수정
- BossRaidResult.cs: Tokens를 Dictionary<string, string>?으로 수정
- GameServer.cs: SendTo(peer) → SendTo(memberPeer) 버그 수정,
  각 파티원에게 개별 토큰 전송

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 12:49:14 +09:00
qornwh1
fb76f49ec0 feat : 보스 전용채널 제거, 채널 5개로 변경, config.json 정리 2026-03-17 10:33:08 +09:00
qornwh1
f8fa34edbc feat : 보스 응답 메시지 문제 수정 2026-03-17 09:15:41 +09:00
7f2cd281da fix: MMO 서버 로직 버그 6건 수정
1. PlayerId 스푸핑 방지: OnTransformPlayer, OnActionPlayer, OnStatePlayer에서
   브로드캐스트 전 packet.PlayerId = hashKey로 강제 교체

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

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

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

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

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

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

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

182
CLAUDE.md Normal file
View File

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

View File

@@ -9,5 +9,5 @@ public sealed class BossRaidResult
public int BossId { get; init; }
public List<string> Players { get; init; } = new();
public string Status { get; init; } = string.Empty;
public string? Tokens { get; init; }
public Dictionary<string, string>? Tokens { get; init; }
}

View File

@@ -35,7 +35,7 @@ public class RestApi : Singleton<RestApi>
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Log.Warning("[RestApi] 토큰 인증 실패 (401)");
return "";
return null;
}
response.EnsureSuccessStatusCode();
@@ -56,7 +56,39 @@ public class RestApi : Singleton<RestApi>
}
}
return "";
return null;
}
// 플레이어 프로필 조회 - 성공 시 PlayerProfileResponse 반환
public async Task<PlayerProfileResponse?> GetPlayerProfileAsync(string username)
{
string url = AppConfig.RestApi.BaseUrl + "/api/internal/player/profile?username=" + Uri.EscapeDataString(username);
for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
{
try
{
HttpResponseMessage response = await httpClient.GetAsync(url);
if (response.StatusCode == HttpStatusCode.NotFound)
{
Log.Warning("[RestApi] 프로필 없음 username={Username}", username);
return null;
}
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<PlayerProfileResponse>();
}
catch (Exception ex) when (attempt < MAX_RETRY)
{
Log.Warning("[RestApi] 프로필 조회 실패 (시도 {Attempt}/{Max}): {Message}", attempt, MAX_RETRY, ex.Message);
await Task.Delay(RETRY_DELAY);
}
catch (Exception ex)
{
Log.Error("[RestApi] 프로필 조회 최종 실패 ({Max}회 시도): {Message}", MAX_RETRY, ex.Message);
}
}
return null;
}
private sealed class AuthVerifyResponse
@@ -69,17 +101,47 @@ public class RestApi : Singleton<RestApi>
}
}
public sealed class PlayerProfileResponse
{
[JsonPropertyName("nickname")]
public string Nickname { get; set; } = string.Empty;
[JsonPropertyName("level")]
public int Level { get; set; }
[JsonPropertyName("experience")]
public int Experience { get; set; }
[JsonPropertyName("nextExp")]
public int NextExp { get; set; }
[JsonPropertyName("maxHp")]
public double MaxHp { get; set; }
[JsonPropertyName("maxMp")]
public double MaxMp { get; set; }
[JsonPropertyName("attackPower")]
public double AttackPower { get; set; }
[JsonPropertyName("attackRange")]
public double AttackRange { get; set; }
[JsonPropertyName("sprintMultiplier")]
public double SprintMultiplier { get; set; }
}
// 레이드 채널 접속 여부 체크
// 성공 시 BossRaidResult 반환, 실패/거절 시 null 반환
public async Task<BossRaidResult?> BossRaidAccesssAsync(List<string> userNames, int bossId)
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++)
{
try
{
HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, new { usernames = userNames, bossId });
HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, new { usernames = userNames, bossId = bossId });
// 401: API 키 인증 실패
if (response.StatusCode == HttpStatusCode.Unauthorized)
@@ -88,10 +150,12 @@ public class RestApi : Singleton<RestApi>
return null;
}
// 400: 입장 조건 미충족 (레벨 부족, 이미 진행중 등)
if (response.StatusCode == HttpStatusCode.BadRequest)
// 400: 입장 조건 미충족 / 409: 이미 레이드 중 등
if (response.StatusCode == HttpStatusCode.BadRequest ||
response.StatusCode == HttpStatusCode.Conflict)
{
Log.Warning("[RestApi] 보스 레이드 입장 거절 (400) BossId={BossId}", bossId);
Log.Warning("[RestApi] 보스 레이드 입장 거절 ({Status}) BossId={BossId}",
(int)response.StatusCode, bossId);
return null;
}
@@ -166,10 +230,10 @@ public class RestApi : Singleton<RestApi>
}
[JsonPropertyName("tokens")]
public string? Tokens
public Dictionary<string, string>? Tokens
{
get;
set;
}
} = new();
}
}

View File

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

View File

@@ -79,9 +79,12 @@ public class Channel
currentMap.RemoveUser(userId);
}
connectUsers.Remove(userId);
if (connectUsers.Remove(userId))
{
UserCount--;
}
connectPeers.Remove(userId);
UserCount--;
}
// 맵 이동 (현재 맵 제거 → 새 맵 추가 → CurrentMapId 갱신)

View File

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

View File

@@ -18,6 +18,9 @@ public 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[]>>
@@ -99,53 +102,80 @@ public class GameServer : ServerBase
OnSessionConnected(peer, hashKey);
}
protected override async void HandleAuth(NetPeer peer, byte[] payload)
protected override async Task HandleAuth(NetPeer peer, byte[] payload)
{
AccTokenPacket accTokenPacket = Serializer.Deserialize<AccTokenPacket>(new ReadOnlyMemory<byte>(payload));
string token = accTokenPacket.Token;
string username = "";
tokenHash.TryGetValue(token, out int hashKey);
if (hashKey <= 1000)
// 동일 토큰 동시 인증 방지
if (!authenticatingTokens.Add(token))
{
hashKey = userUuidGenerator.Create();
Log.Warning("[Server] 동일 토큰 동시 인증 시도 차단 PeerId={Id}", peer.Id);
peer.Disconnect();
return;
}
if (sessions.TryGetValue(hashKey, out NetPeer? existing))
try
{
// WiFi → LTE 전환 등 재연결: 이전 피어 교체 (토큰 재검증 불필요)
existing.Tag = null;
sessions.Remove(hashKey);
Log.Information("[Server] 재연결 HashKey={Key} Old={Old} New={New}", hashKey, existing.Id, peer.Id);
existing.Disconnect();
}
else
{
// 신규 연결: 웹서버에 JWT 검증 요청
username = await RestApi.Instance.VerifyTokenAsync(token);
if (username == null)
string? username = "";
int hashKey;
bool isReconnect;
lock (sessionLock)
{
Log.Warning("[Server] 토큰 검증 실패 - 연결 거부 PeerId={Id}", peer.Id);
userUuidGenerator.Release(hashKey);
peer.Disconnect();
return;
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();
}
}
Log.Information("[Server] 토큰 검증 성공 Username={Username} PeerId={Id}", username, peer.Id);
}
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;
}
peer.Tag = new Session(hashKey, peer);
((Session)peer.Tag).Token = token;
if (username.Length > 0)
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
{
((Session)peer.Tag).UserName = username;
authenticatingTokens.Remove(token);
}
sessions[hashKey] = peer;
tokenHash[token] = hashKey;
pendingPeers.Remove(peer.Id);
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
OnSessionConnected(peer, hashKey);
}
protected override void OnSessionConnected(NetPeer peer, int hashKey)
@@ -335,7 +365,7 @@ public class GameServer : ServerBase
{
IsAccepted = true,
Player = ToPlayerInfo(player),
MaplId = channelId
MapId = player.CurrentMapId
};
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.LOAD_GAME, packet);
@@ -406,7 +436,12 @@ public class GameServer : ServerBase
Mp = player.Mp,
MaxMp = player.MaxMp,
Position = new Position { X = player.PosX, Y = player.PosY, Z = player.PosZ },
RotY = player.RotY
RotY = player.RotY,
Experience = player.Experience,
NextExp = player.NextExp,
AttackPower = player.AttackPower,
AttackRange = player.AttackRange,
SprintMultiplier = player.SprintMultiplier,
};
}
@@ -414,7 +449,7 @@ public class GameServer : ServerBase
// 패킷 핸들러
// ============================================================
private void OnIntoChannel(NetPeer peer, int hashKey, byte[] payload)
private async void OnIntoChannel(NetPeer peer, int hashKey, byte[] payload)
{
IntoChannelPacket packet = Serializer.Deserialize<IntoChannelPacket>(new ReadOnlyMemory<byte>(payload));
@@ -422,10 +457,10 @@ public class GameServer : ServerBase
// 이전에 다른 채널에 있었는지 체크
int preChannelId = cm.HasUser(hashKey);
Player? prevPlayer = preChannelId >= 0 ? cm.GetChannel(preChannelId).GetPlayer(hashKey) : null;
if (preChannelId >= 0)
{
// 제거 전에 채널/플레이어 정보 저장 (브로드캐스트에 필요)
Player? player = cm.GetChannel(preChannelId).GetPlayer(hashKey);
Player? player = prevPlayer;
// 파티 자동 탈퇴
HandlePartyLeaveOnExit(preChannelId, hashKey);
@@ -447,21 +482,64 @@ public class GameServer : ServerBase
{
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;
}
// TODO: 실제 서비스에서는 DB/세션에서 플레이어 정보 로드 필요
Player newPlayer = new()
// API 서버에서 플레이어 프로필 로드
Player newPlayer = new Player
{
HashKey = hashKey,
PlayerId = hashKey,
Nickname = ((Session)peer.Tag).UserName
Nickname = ((Session)peer.Tag).Username ?? ""
};
// 채널에 추가
Session? session = peer.Tag as Session;
string? username = session?.Username;
if (!string.IsNullOrEmpty(username))
{
try
{
RestApi.PlayerProfileResponse? profile = await RestApi.Instance.GetPlayerProfileAsync(username);
if (profile != null)
{
newPlayer.Nickname = string.IsNullOrEmpty(profile.Nickname) ? username : profile.Nickname;
newPlayer.Level = profile.Level;
newPlayer.MaxHp = (int)profile.MaxHp;
newPlayer.Hp = (int)profile.MaxHp;
newPlayer.MaxMp = (int)profile.MaxMp;
newPlayer.Mp = (int)profile.MaxMp;
newPlayer.Experience = profile.Experience;
newPlayer.NextExp = profile.NextExp;
newPlayer.AttackPower = (float)profile.AttackPower;
newPlayer.AttackRange = (float)profile.AttackRange;
newPlayer.SprintMultiplier = (float)profile.SprintMultiplier;
Log.Information("[GameServer] 프로필 로드 완료 Username={Username} Level={Level} MaxHp={MaxHp}",
username, profile.Level, profile.MaxHp);
}
else
{
newPlayer.Nickname = username;
Log.Warning("[GameServer] 프로필 로드 실패 — 기본값 사용 Username={Username}", username);
}
}
catch (Exception ex)
{
newPlayer.Nickname = username;
Log.Error(ex, "[GameServer] 프로필 로드 예외 Username={Username}", username);
}
}
cm.AddUser(packet.ChannelId, hashKey, newPlayer, peer);
Log.Debug("[GameServer] INTO_CHANNEL HashKey={Key} ChannelId={ChannelId}", hashKey, packet.ChannelId);
@@ -507,12 +585,19 @@ public class GameServer : ServerBase
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 (preChannelId < 0 || preParty == null)
if (preParty == null)
{
Log.Warning("[GameServer] INTO_CHANNEL_PARTY 해당 파티 없음");
return;
@@ -533,12 +618,15 @@ public class GameServer : ServerBase
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 = ToPlayerInfo(player),
@@ -574,12 +662,13 @@ public class GameServer : ServerBase
if (memberPeer != null)
{
// 새 채널에 유저 추가
// 새 채널에 유저 추가 (보존된 플레이어 정보 사용)
string nickname = savedPlayers.TryGetValue(memberId, out Player? saved) ? saved.Nickname : memberId.ToString();
Player newPlayer = new()
{
HashKey = memberId,
PlayerId = memberId,
Nickname = memberId.ToString()
Nickname = nickname
};
cm.AddUser(packet.ChannelId, memberId, newPlayer, memberPeer);
@@ -923,10 +1012,24 @@ public class GameServer : ServerBase
}
int oldMapId = player.CurrentMapId;
int newMapId = packet.MapId;
if (!channel.ChangeMap(hashKey, player, packet.MapId))
// 일단 보스맵에서 로비로 원복할떄 캐싱해둔 걸로 교체
if (newMapId == -1)
{
Log.Warning("[GameServer] CHANGE_MAP 유효하지 않은 맵 HashKey={Key} MapId={MapId}", hashKey, packet.MapId);
if (player.PreviousMapId > 0)
{
// 레이드 맵 사용 종료 처리
channel.RemoveInstanceMap(oldMapId);
newMapId = player.PreviousMapId;
player.PreviousMapId = 0;
}
}
if (!channel.ChangeMap(hashKey, player, newMapId))
{
Log.Warning("[GameServer] CHANGE_MAP 유효하지 않은 맵 HashKey={Key} MapId={MapId}", hashKey, newMapId);
return;
}
@@ -937,12 +1040,12 @@ public class GameServer : ServerBase
BroadcastToMap(channelId, oldMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, exitNotify));
// 새 맵 유저들에게 입장 알림 (본인 제외)
ChangeMapPacket enterNotify = new() { MapId = packet.MapId, IsAdd = true, Player = playerInfo };
BroadcastToMap(channelId, packet.MapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, enterNotify), peer);
ChangeMapPacket enterNotify = new() { MapId = newMapId, IsAdd = true, Player = playerInfo };
BroadcastToMap(channelId, newMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, enterNotify), peer);
// 본인에게 새 맵 플레이어 목록 전달
ChangeMapPacket response = new() { MapId = packet.MapId };
AMap? newMap = channel.GetMap(packet.MapId);
ChangeMapPacket response = new() { MapId = newMapId };
AMap? newMap = channel.GetMap(newMapId);
if (newMap != null)
{
foreach ((int uid, Player p) in newMap.GetUsers())
@@ -1037,7 +1140,16 @@ public class GameServer : ServerBase
Log.Debug("[GameServer] PARTY_CHANGE_MAP HashKey={Key} PartyId={PartyId} MapId={MapId}", hashKey, packet.PartyId, packet.MapId);
}
private async void OnIntoBossRaid(NetPeer peer, int hashKey, byte[] payload)
private void OnIntoBossRaid(NetPeer peer, int hashKey, byte[] payload)
{
_ = OnIntoBossRaidAsync(peer, hashKey, payload).ContinueWith(t =>
{
if (t.IsFaulted)
Log.Error(t.Exception, "[GameServer] OnIntoBossRaid 예외 HashKey={Key}", hashKey);
}, TaskContinuationOptions.OnlyOnFaulted);
}
private async Task OnIntoBossRaidAsync(NetPeer peer, int hashKey, byte[] payload)
{
IntoBossRaidPacket packet = Serializer.Deserialize<IntoBossRaidPacket>(new ReadOnlyMemory<byte>(payload));
@@ -1072,86 +1184,113 @@ public class GameServer : ServerBase
// API로 접속 체크
List<string> userNames = new List<string>();
foreach (int memberId in party.PartyMemberIds)
{
userNames.Add(channel.GetPlayer(memberId).Nickname);
}
BossRaidResult? result = await RestApi.Instance.BossRaidAccesssAsync(userNames, 1);
// 입장 실패
if (result == null || result.BossId <= 0)
{
SendTo(peer,
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket { RaidId = -1, IsSuccess = false }));
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId} Failed", hashKey,
party.PartyId, -1);
return;
}
// 레이드 맵 할당 (미사용 맵 탐색 → 없으면 동적 생성)
int assignedRaidMapId = channel.GetOrCreateAvailableRaidMap();
// 진행중 맵으로 등록
channel.AddInstanceMap(assignedRaidMapId);
// 파티원 전체 레이드 맵으로 이동 + 각자에게 알림
foreach (int memberId in party.PartyMemberIds)
{
Player? memberPlayer = channel.GetPlayer(memberId);
if (memberPlayer == null)
if (memberPlayer != null)
{
continue;
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 }));
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId} Failed", hashKey,
party.PartyId, -1);
return;
}
// 이전 맵 캐싱 (레이드 종료 후 복귀용)
memberPlayer.PreviousMapId = memberPlayer.CurrentMapId;
int oldMapId = memberPlayer.CurrentMapId;
channel.ChangeMap(memberId, memberPlayer, assignedRaidMapId);
if (!sessions.TryGetValue(memberId, out NetPeer? memberPeer))
// await 이후 상태 재검증
channelId = cm.HasUser(hashKey);
if (channelId < 0)
{
continue;
return;
}
PlayerInfo memberInfo = ToPlayerInfo(memberPlayer);
// 기존 맵 유저들에게 퇴장 알림
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)
channel = cm.GetChannel(channelId);
party = channel.GetPartyManager().GetPartyByPlayer(hashKey);
if (party == null)
{
foreach ((int uid, Player p) in raidMap.GetUsers())
return;
}
// 레이드 맵 할당 (미사용 맵 탐색 → 없으면 동적 생성)
int assignedRaidMapId = channel.GetOrCreateAvailableRaidMap();
// 진행중 맵으로 등록
channel.AddInstanceMap(assignedRaidMapId);
// 파티원 전체 레이드 맵으로 이동 + 각자에게 알림
foreach (int memberId in party.PartyMemberIds)
{
Player? memberPlayer = channel.GetPlayer(memberId);
if (memberPlayer == null)
{
if (uid != memberId)
continue;
}
// 이전 맵 캐싱 (레이드 종료 후 복귀용)
memberPlayer.PreviousMapId = memberPlayer.CurrentMapId;
int oldMapId = memberPlayer.CurrentMapId;
channel.ChangeMap(memberId, memberPlayer, assignedRaidMapId);
if (!sessions.TryGetValue(memberId, out NetPeer? memberPeer))
{
continue;
}
PlayerInfo memberInfo = ToPlayerInfo(memberPlayer);
// 기존 맵 유저들에게 퇴장 알림
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 p) in raidMap.GetUsers())
{
response.Players.Add(ToPlayerInfo(p));
if (uid != memberId)
{
response.Players.Add(ToPlayerInfo(p));
}
}
}
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
: ""
}));
}
SendTo(memberPeer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
// 모두에게 레이드로 이동 (할당된 실제 레이드 맵 ID 전달)
SendTo(peer,
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket
{ RaidId = assignedRaidMapId, IsSuccess = true, Session = result.SessionName, Token = result.Tokens }));
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId}", hashKey, party.PartyId,
assignedRaidMapId);
}
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId}", hashKey, party.PartyId,
assignedRaidMapId);
}
// 채널 퇴장/연결 해제 시 파티 자동 탈퇴 처리
@@ -1167,8 +1306,8 @@ public class GameServer : ServerBase
pm.LeaveParty(hashKey, out PartyInfo? remaining);
// 0명 → DELETE, 남은 멤버 있음 → LEAVE
UpdatePartyPacket notify = remaining != null
// 남은 멤버 있음 → LEAVE, 0명(파티 해산됨) → DELETE
UpdatePartyPacket notify = remaining != null && remaining.PartyMemberIds.Count > 0
? new UpdatePartyPacket
{
PartyId = partyId.Value,

View File

@@ -28,6 +28,12 @@ public class PartyManager
memeberIds = new List<int>();
}
// 리더 중복 방지: 기존 멤버 목록에 리더가 없을 때만 추가
if (!memeberIds.Contains(leaderId))
{
memeberIds.Add(leaderId);
}
party = new PartyInfo
{
PartyId = partyId,
@@ -35,10 +41,14 @@ public class PartyManager
PartyName = partyName,
PartyMemberIds = memeberIds
};
party.PartyMemberIds.Add(leaderId);
parties[partyId] = party;
playerPartyMap[leaderId] = partyId;
// 모든 멤버를 playerPartyMap에 등록
foreach (int memberId in memeberIds)
{
playerPartyMap[memberId] = partyId;
}
return true;
}

View File

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

View File

@@ -198,7 +198,7 @@ public class LoadGamePacket
}
[ProtoMember(3)]
public int MaplId
public int MapId
{
get;
set;

View File

@@ -2,73 +2,73 @@ namespace MMOserver.Packet;
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 = 1000,
// DUMMY 클라는 이걸로 jwt토큰 안받음
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
}

View File

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

View File

@@ -42,6 +42,9 @@ public abstract class ServerBase : INetEventListener
// 재사용 NetDataWriter (단일 스레드 폴링이므로 안전)
private readonly NetDataWriter cachedWriter = new();
// async 메서드(HandleAuth 등)의 await 이후 공유 자원 접근 보호용
protected readonly object sessionLock = new();
// 핑 로그 출력 여부
public bool PingLogRtt
{
@@ -118,26 +121,29 @@ public abstract class ServerBase : INetEventListener
// 클라이언트가 연결 해제됐을 때 (타임아웃, 명시적 끊기 등)
public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
{
pendingPeers.Remove(peer.Id);
if (peer.Tag is Session session)
lock (sessionLock)
{
// 현재 인증된 피어가 이 peer일 때만 세션 제거
// (재연결로 이미 교체된 경우엔 건드리지 않음)
if (sessions.TryGetValue(session.HashKey, out NetPeer? current) && current.Id == peer.Id)
pendingPeers.Remove(peer.Id);
if (peer.Tag is Session session)
{
// 더미 클라 아니면 token관리
if (!string.IsNullOrEmpty(session.Token))
// 현재 인증된 피어가 이 peer일 때만 세션 제거
// (재연결로 이미 교체된 경우엔 건드리지 않음)
if (sessions.TryGetValue(session.HashKey, out NetPeer? current) && current.Id == peer.Id)
{
tokenHash.Remove(session.Token);
// 더미 클라 아니면 token관리
if (!string.IsNullOrEmpty(session.Token))
{
tokenHash.Remove(session.Token);
}
sessions.Remove(session.HashKey);
Log.Information("[Server] 세션 해제 HashKey={Key} Reason={Reason}", session.HashKey, disconnectInfo.Reason);
OnSessionDisconnected(peer, session.HashKey, disconnectInfo);
}
sessions.Remove(session.HashKey);
Log.Information("[Server] 세션 해제 HashKey={Key} Reason={Reason}", session.HashKey, disconnectInfo.Reason);
OnSessionDisconnected(peer, session.HashKey, disconnectInfo);
peer.Tag = null;
}
peer.Tag = null;
}
}
@@ -167,7 +173,11 @@ public abstract class ServerBase : INetEventListener
// Auth 패킷은 베이스에서 처리 (raw 8-byte long, protobuf 불필요)
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;
}
else if (type == (ushort)PacketType.DUMMY_ACC_TOKEN)
@@ -240,7 +250,7 @@ public abstract class ServerBase : INetEventListener
// ─── Auth 처리 ────────────────────────────────────────────────
protected abstract void HandleAuth(NetPeer peer, byte[] payload);
protected abstract Task HandleAuth(NetPeer peer, byte[] payload);
// ─── 전송 헬퍼 ───────────────────────────────────────────────────────

View File

@@ -10,18 +10,18 @@ public class Session
set;
}
public string? Username
{
get;
set;
}
public int HashKey
{
get;
init;
}
public string UserName
{
get;
set;
}
public NetPeer Peer
{
get;