19 Commits

Author SHA1 Message Date
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
7f2cd281da fix: MMO 서버 로직 버그 6건 수정
1. PlayerId 스푸핑 방지: OnTransformPlayer, OnActionPlayer, OnStatePlayer에서
   브로드캐스트 전 packet.PlayerId = hashKey로 강제 교체

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

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

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

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

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

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 00:34:40 +09:00
qornwh1
39ef81d48a fix : 일단 메시지body 임시 처리 (hp, 경험치, 파워 등) 2026-03-16 20:47:22 +09:00
qornwh1
6faab45ecc feat : 레이드 이동 메시지 수정 모두에게 2026-03-16 20:36:24 +09:00
qornwh1
dd8dcc58d2 feat : 보스레이드 신청 메시지 응답 패킷 구현 2026-03-16 19:19:59 +09:00
qornwh1
f6b378cad7 feat : 보스 레이드 입장 메시지 기능 추가 2026-03-16 17:55:08 +09:00
qornwh1
943302c2f1 fix : 맵 이동시 유저 진입 동기화버그 수정 2026-03-16 16:07:49 +09:00
qornwh1
523247c9b1 fea : Map단위로 캐릭터 이동 메시지 전달기능 추가 2026-03-16 15:16:42 +09:00
qornwh1
e4429177db feat : 맵관리 코드 추가 작업 2026-03-16 14:50:29 +09:00
qornwh1
f564199cb5 fix : 변수 네이밍 수정 2026-03-16 11:27:07 +09:00
qornwh1
f2bc3d7924 fix : 서버 설정파일 빼기 작업 2026-03-16 11:14:38 +09:00
qornwh1
f6067047d9 fix : 토큰인증 스펙 수정 2026-03-16 10:43:30 +09:00
qornwh1
2bc01f9c18 fix : 토큰 인증 수정 2026-03-16 10:22:00 +09:00
qornwh1
3d62cbf58d feat : Vector3 int -> float, 이동시 int 캐스팅 제거, 프로그램 실행시 setting.json 추가 2026-03-12 16:49:23 +09:00
qornwh1
d626a7156d feat : 보스 채널은 안띄운다. 2026-03-12 16:09:13 +09:00
qornwh1
0ebe269146 feat : 보스전 채널 생성, 파티 함께 채널 이동 구현 2026-03-12 13:23:30 +09:00
qornwh1
4956a2e26d 도커 파일 포트 접속 추가 2026-03-11 19:45:50 +09:00
qornwh1
6e8a9c0b5e feat : 파티용 패킷 수정,
파티 CRUD 버그 수정
2026-03-11 19:36:00 +09:00
qornwh1
056ec8d0c3 feat : 파티 정보 업데이트 기능 추가 2026-03-11 15:09:06 +09:00
28 changed files with 1682 additions and 240 deletions

View File

@@ -125,8 +125,8 @@ public class DummyClients
distance = hitWall ? 0f : distance - step; distance = hitWall ? 0f : distance - step;
// 정수 Vector3 갱신 // 정수 Vector3 갱신
position.X = (int)MathF.Round(posX); position.X = posX;
position.Z = (int)MathF.Round(posZ); position.Z = posZ;
} }
public void SendTransform() public void SendTransform()
@@ -144,7 +144,7 @@ public class DummyClients
Position = new Packet.Position Position = new Packet.Position
{ {
X = position.X, X = position.X,
Y = 0, // 높이는 버린다. Y = -0.5f, // 높이는 버린다.
Z = position.Z Z = position.Z
} }
}; };

View File

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

View File

@@ -210,7 +210,42 @@ public class LoadChannelPacket
} = new List<ChannelInfo>(); } = new List<ChannelInfo>();
} }
// INTO_CHANNEL 클라->서버: 입장할 채널 ID / 서버->클라: 채널 내 나 이외 플레이어 목록 // 채널 내 파티 정보 (INTO_CHANNEL 응답에 포함)
[ProtoContract]
public class PartyInfoData
{
[ProtoMember(1)]
public int PartyId
{
get;
set;
}
[ProtoMember(2)]
public int LeaderId
{
get;
set;
}
[ProtoMember(3)]
public List<int> MemberPlayerIds
{
get;
set;
} = new List<int>();
[ProtoMember(4)]
public string PartyName
{
get;
set;
}
}
// INTO_CHANNEL
// 클라->서버: 입장할 채널 ID
// 서버->클라: 채널 내 나 이외 플레이어 목록
[ProtoContract] [ProtoContract]
public class IntoChannelPacket public class IntoChannelPacket
{ {
@@ -227,6 +262,47 @@ public class IntoChannelPacket
get; get;
set; set;
} = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록 } = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록
[ProtoMember(3)]
public List<PartyInfoData> Parties
{
get;
set;
} = new List<PartyInfoData>(); // 서버->클라: 채널 내 파티 목록
}
// 파티원 모두 채널이동
// 클라->서버: 입장할 채널 ID
[ProtoContract]
public class IntoChannelPartyPacket
{
[ProtoMember(1)]
public int ChannelId
{
get;
set;
} // 클라->서버: 입장할 채널 ID
[ProtoMember(2)]
public List<PlayerInfo> Players
{
get;
set;
} = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록
[ProtoMember(3)]
public List<PartyInfoData> Parties
{
get;
set;
} = new List<PartyInfoData>(); // 서버->클라: 채널 내 파티 목록
[ProtoMember(4)]
public int PartyId
{
get;
set;
}
} }
// UPDATE_CHANNEL_USER 유저 접속/나감 // UPDATE_CHANNEL_USER 유저 접속/나감
@@ -524,9 +600,10 @@ public enum ErrorCode : int
{ {
// 파티 (10021~) // 파티 (10021~)
PARTY_ALREADY_IN_PARTY = 10021, PARTY_ALREADY_IN_PARTY = 10021,
PARTY_JOIN_FAILED = 10022, PARTY_JOIN_FAILED = 10022,
PARTY_NOT_IN_PARTY = 10023, PARTY_NOT_IN_PARTY = 10023,
PARTY_DELETE_FAILED = 10024, PARTY_DELETE_FAILED = 10024,
PARTY_UPDATE_FAILED = 10025,
} }
// ERROR (서버 -> 클라) // ERROR (서버 -> 클라)
@@ -550,7 +627,8 @@ public enum PartyUpdateType
CREATE, CREATE,
DELETE, DELETE,
JOIN, JOIN,
LEAVE LEAVE,
UPDATE
} }
// REQUEST_PARTY (클라 -> 서버) - CREATE: PartyName 사용 / JOIN·LEAVE·DELETE: PartyId 사용 // REQUEST_PARTY (클라 -> 서버) - CREATE: PartyName 사용 / JOIN·LEAVE·DELETE: PartyId 사용
@@ -585,9 +663,9 @@ public class RequestPartyPacket
public enum ChatType public enum ChatType
{ {
GLOBAL, // 전체 채널 GLOBAL, // 전체 채널
PARTY, // 파티원 PARTY, // 파티원
WHISPER // 귓말 WHISPER // 귓말
} }
// CHAT (클라 -> 서버 & 서버 -> 클라) // CHAT (클라 -> 서버 & 서버 -> 클라)

View File

@@ -21,6 +21,9 @@ public enum PacketCode : ushort
// 나 채널 접속 (클라 -> 서버) // 나 채널 접속 (클라 -> 서버)
INTO_CHANNEL, INTO_CHANNEL,
// 파티 채널 접속 (클라 -> 서버)
INTO_CHANNEL_PARTY,
// 새로운 유저 채널 접속 (서버 -> 클라) / 유저 채널 나감 (서버 -> 클라) // 새로운 유저 채널 접속 (서버 -> 클라) / 유저 채널 나감 (서버 -> 클라)
UPDATE_CHANNEL_USER, UPDATE_CHANNEL_USER,

View File

@@ -1,3 +1,4 @@
using System.Text.Json;
using ClientTester.DummyService; using ClientTester.DummyService;
using ClientTester.EchoDummyService; using ClientTester.EchoDummyService;
using ClientTester.StressTest; using ClientTester.StressTest;
@@ -8,9 +9,23 @@ class EcoClientTester
{ {
public static string SERVER_IP = "localhost"; public static string SERVER_IP = "localhost";
public static int SERVER_PORT = 9500; public static int SERVER_PORT = 9500;
public static readonly string CONNECTION_KEY = "test"; public static string CONNECTION_KEY = "";
public static int CLIENT_COUNT = 50; public static int CLIENT_COUNT = 50;
private static void LoadConfig()
{
string path = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
if (!File.Exists(path)) return;
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path));
JsonElement root = doc.RootElement;
if (root.TryGetProperty("ServerIp", out JsonElement ip)) SERVER_IP = ip.GetString() ?? SERVER_IP;
if (root.TryGetProperty("ServerPort", out JsonElement port)) SERVER_PORT = port.GetInt32();
if (root.TryGetProperty("ConnectionKey", out JsonElement key)) CONNECTION_KEY = key.GetString() ?? CONNECTION_KEY;
if (root.TryGetProperty("ClientCount", out JsonElement count)) CLIENT_COUNT = count.GetInt32();
}
private async Task StartEchoDummyTest() private async Task StartEchoDummyTest()
{ {
try try
@@ -151,6 +166,9 @@ class EcoClientTester
// 유니코드 문자(═, ║ 등) 콘솔 깨짐 방지 // 유니코드 문자(═, ║ 등) 콘솔 깨짐 방지
Console.OutputEncoding = System.Text.Encoding.UTF8; Console.OutputEncoding = System.Text.Encoding.UTF8;
// appsettings.json 에서 설정 로드
LoadConfig();
// 크래시 덤프 핸들러 (Release: .log + .dmp / Debug: .log) // 크래시 덤프 핸들러 (Release: .log + .dmp / Debug: .log)
CrashDumpHandler.Register(); CrashDumpHandler.Register();
@@ -169,7 +187,7 @@ class EcoClientTester
if (args.Length > 0 && args[0].Equals("stress", StringComparison.OrdinalIgnoreCase)) if (args.Length > 0 && args[0].Equals("stress", StringComparison.OrdinalIgnoreCase))
{ {
// 기본값 // 기본값
CLIENT_COUNT = 50; // CLIENT_COUNT = 50;
int duration = 60; int duration = 60;
int sendInterval = 100; int sendInterval = 100;
int rampInterval = 1000; int rampInterval = 1000;

View File

@@ -144,15 +144,15 @@ public class StressTestClient
posX = nextX; posX = nextX;
posZ = nextZ; posZ = nextZ;
distance = hitWall ? 0f : distance - step; distance = hitWall ? 0f : distance - step;
position.X = (int)MathF.Round(posX); position.X = posX;
position.Z = (int)MathF.Round(posZ); position.Z = posZ;
// 전송 // 전송
TransformPlayerPacket pkt = new TransformPlayerPacket TransformPlayerPacket pkt = new TransformPlayerPacket
{ {
PlayerId = clientId, PlayerId = clientId,
RotY = rotY, RotY = rotY,
Position = new Packet.Position { X = position.X, Y = 0, Z = position.Z } Position = new Packet.Position { X = position.X, Y = -0.5f, Z = position.Z }
}; };
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.TRANSFORM_PLAYER, pkt); byte[] data = PacketSerializer.Serialize((ushort)PacketCode.TRANSFORM_PLAYER, pkt);
writer.Put(data); writer.Put(data);

View File

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

View File

@@ -0,0 +1,6 @@
{
"ServerIp": "localhost",
"ServerPort": 9500,
"ConnectionKey": "test",
"ClientCount": 80
}

View File

@@ -0,0 +1,13 @@
namespace MMOserver.Api;
// RestApi.BossRaidAccesssAsync 반환용 도메인 모델
// API 응답(BossRaidAccessResponse)을 직접 노출하지 않고 이걸로 매핑해서 반환
public sealed class BossRaidResult
{
public int RoomId { get; init; }
public string SessionName { get; init; } = string.Empty;
public int BossId { get; init; }
public List<string> Players { get; init; } = new();
public string Status { get; init; } = string.Empty;
public Dictionary<string, string>? Tokens { get; init; }
}

View File

@@ -1,6 +1,7 @@
using System.Net; using System.Net;
using System.Net.Http.Json; using System.Net.Http.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using MMOserver.Config;
using MMOserver.Utils; using MMOserver.Utils;
using Serilog; using Serilog;
@@ -8,22 +9,27 @@ namespace MMOserver.Api;
public class RestApi : Singleton<RestApi> public class RestApi : Singleton<RestApi>
{ {
private const string VERIFY_URL = "https://a301.api.tolelom.xyz/api/auth/verify";
private readonly HttpClient httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) }; 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);
public RestApi()
{
httpClient.DefaultRequestHeaders.Add("X-API-Key", AppConfig.RestApi.ApiKey);
}
// 토큰 검증 - 성공 시 username 반환 // 토큰 검증 - 성공 시 username 반환
// 401 → 재시도 없이 즉시 null 반환 (토큰 자체가 무효) // 401 → 재시도 없이 즉시 null 반환 (토큰 자체가 무효)
// 타임아웃/네트워크 오류 → 최대 MAX_RETRY회 재시도 후 null 반환 // 타임아웃/네트워크 오류 → 최대 MAX_RETRY회 재시도 후 null 반환
public async Task<string?> VerifyTokenAsync(string token) public async Task<string?> VerifyTokenAsync(string token)
{ {
string url = AppConfig.RestApi.BaseUrl + AppConfig.RestApi.VerifyToken;
for (int attempt = 1; attempt <= MAX_RETRY; attempt++) for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
{ {
try try
{ {
HttpResponseMessage response = await httpClient.PostAsJsonAsync(VERIFY_URL, new { token }); HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, new { token });
// 401: 토큰 자체가 무효 → 재시도해도 같은 결과, 즉시 반환 // 401: 토큰 자체가 무효 → 재시도해도 같은 결과, 즉시 반환
if (response.StatusCode == HttpStatusCode.Unauthorized) if (response.StatusCode == HttpStatusCode.Unauthorized)
@@ -62,4 +68,110 @@ public class RestApi : Singleton<RestApi>
set; set;
} }
} }
// 레이드 채널 접속 여부 체크
// 성공 시 BossRaidResult 반환, 실패/거절 시 null 반환
public async Task<BossRaidResult?> BossRaidAccessAsync(List<string> userNames, int bossId)
{
string url = AppConfig.RestApi.BaseUrl + "/api/internal/bossraid/entry";
for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
{
try
{
HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, new { usernames = userNames, bossId });
// 401: API 키 인증 실패
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Log.Warning("[RestApi] 보스 레이드 접속 인증 실패 (401)");
return null;
}
// 400: 입장 조건 미충족 / 409: 이미 레이드 중 등
if (response.StatusCode == HttpStatusCode.BadRequest ||
response.StatusCode == HttpStatusCode.Conflict)
{
Log.Warning("[RestApi] 보스 레이드 입장 거절 ({Status}) BossId={BossId}",
(int)response.StatusCode, bossId);
return null;
}
response.EnsureSuccessStatusCode();
BossRaidAccessResponse? raw = await response.Content.ReadFromJsonAsync<BossRaidAccessResponse>();
if (raw == null)
{
return null;
}
// API 응답 → 도메인 모델 매핑
return new BossRaidResult
{
RoomId = raw.RoomId,
SessionName = raw.SessionName ?? string.Empty,
BossId = raw.BossId,
Players = raw.Players,
Status = raw.Status ?? string.Empty,
Tokens = raw.Tokens
};
}
catch (Exception ex) when (attempt < MAX_RETRY)
{
Log.Warning("[RestApi] 보스 레이드 통신 실패 (시도 {Attempt}/{Max}): {Message}", attempt, MAX_RETRY, ex.Message);
await Task.Delay(RETRY_DELAY);
}
catch (Exception ex)
{
Log.Error("[RestApi] 보스 레이드 최종 통신 실패 ({Max}회 시도): {Message}", MAX_RETRY, ex.Message);
}
}
return null;
}
private sealed class BossRaidAccessResponse
{
[JsonPropertyName("roomId")]
public int RoomId
{
get;
set;
}
[JsonPropertyName("sessionName")]
public string? SessionName
{
get;
set;
}
[JsonPropertyName("bossId")]
public int BossId
{
get;
set;
}
[JsonPropertyName("players")]
public List<string> Players
{
get;
set;
} = new();
[JsonPropertyName("status")]
public string? Status
{
get;
set;
}
[JsonPropertyName("tokens")]
public Dictionary<string, string>? Tokens
{
get;
set;
}
}
} }

View File

@@ -0,0 +1,62 @@
using Microsoft.Extensions.Configuration;
namespace MMOserver.Config;
public static class AppConfig
{
public static ServerConfig Server
{
get;
private set;
} = null!;
public static RestApiConfig RestApi
{
get;
private set;
} = null!;
public static void Initialize(IConfiguration config)
{
Server = new ServerConfig(config.GetSection("Server"));
RestApi = new RestApiConfig(config.GetSection("RestApi"));
}
}
public sealed class ServerConfig
{
public int Port
{
get;
}
public ServerConfig(IConfigurationSection section)
{
Port = int.Parse(section["Port"] ?? throw new InvalidOperationException("Server:Port is required in config.json"));
}
}
public sealed class RestApiConfig
{
public string BaseUrl
{
get;
}
public string VerifyToken
{
get;
}
public string ApiKey
{
get;
}
public RestApiConfig(IConfigurationSection section)
{
BaseUrl = section["BaseUrl"] ?? throw new InvalidOperationException("RestApi:BaseUrl is required in config.json");
VerifyToken = section["VerifyToken"] ?? throw new InvalidOperationException("RestApi:BaseUrl is required in config.json");
ApiKey = section["ApiKey"] ?? throw new InvalidOperationException("RestApi:ApiKey is required in config.json");
}
}

View File

@@ -1,27 +1,51 @@
using LiteNetLib; using LiteNetLib;
using MMOserver.Game.Channel.Maps; using MMOserver.Game.Channel.Maps;
using MMOserver.Game.Channel.Maps.InstanceDungeun;
using MMOserver.Game.Party; using MMOserver.Game.Party;
namespace MMOserver.Game.Channel; namespace MMOserver.Game.Channel;
public class Channel public class Channel
{ {
// 로비 // 채널 내 유저 NetPeer (hashKey → NetPeer) — BroadcastToChannel 교차 조회 제거용
private Robby robby = new Robby(); private readonly Dictionary<int, NetPeer> connectPeers = new();
// 파티
private PartyManager partyManager = new PartyManager();
// 채널 내 유저 상태 (hashKey → Player) // 채널 내 유저 상태 (hashKey → Player)
private Dictionary<int, Player> connectUsers = new Dictionary<int, Player>(); private readonly Dictionary<int, Player> connectUsers = new();
// 채널 내 유저 NetPeer (hashKey → NetPeer) — BroadcastToChannel 교차 조회 제거용 // 채널 맵 관리
private Dictionary<int, NetPeer> connectPeers = new Dictionary<int, NetPeer>(); private readonly Dictionary<int, AMap> maps = new();
// 진행중 채널 맵 관리
private readonly Dictionary<int, AMap> useInstanceMaps = new();
// 동적 레이드 맵 할당용 ID 카운터 (사전 생성 10개 이후부터 시작)
private int nextDynamicRaidMapId = 1011;
// 파티
private readonly PartyManager partyManager = new();
public Channel(int channelId)
{
ChannelId = channelId;
// 일단 하드코딩으로 맵 생성
{
// 로비
maps.Add(1, new Robby(1));
// 인던
int defaultValue = 1000;
for (int i = 1; i <= 10; i++)
{
maps.Add(i + defaultValue, new BossInstance(i + defaultValue));
}
}
}
public int ChannelId public int ChannelId
{ {
get; get;
private set;
} }
public int UserCount public int UserCount
@@ -36,23 +60,50 @@ public class Channel
private set; private set;
} = 100; } = 100;
public Channel(int channelId)
{
ChannelId = channelId;
}
public void AddUser(int userId, Player player, NetPeer peer) public void AddUser(int userId, Player player, NetPeer peer)
{ {
connectUsers[userId] = player; connectUsers[userId] = player;
connectPeers[userId] = peer; connectPeers[userId] = peer;
UserCount++; UserCount++;
// 처음 접속 시 1번 맵(로비)으로 입장
ChangeMap(userId, player, 1);
} }
public void RemoveUser(int userId) public void RemoveUser(int userId)
{ {
connectUsers.Remove(userId); // 현재 맵에서도 제거
if (connectUsers.TryGetValue(userId, out Player? player) &&
maps.TryGetValue(player.CurrentMapId, out AMap? currentMap))
{
currentMap.RemoveUser(userId);
}
if (connectUsers.Remove(userId))
{
UserCount--;
}
connectPeers.Remove(userId); connectPeers.Remove(userId);
UserCount--; }
// 맵 이동 (현재 맵 제거 → 새 맵 추가 → CurrentMapId 갱신)
public bool ChangeMap(int userId, Player player, int mapId)
{
if (!maps.TryGetValue(mapId, out AMap? newMap))
{
return false;
}
// 기존 맵에서 제거
if (maps.TryGetValue(player.CurrentMapId, out AMap? oldMap))
{
oldMap.RemoveUser(userId);
}
newMap.AddUser(userId, player);
player.CurrentMapId = mapId;
return true;
} }
// 재연결(WiFi→LTE 등) 시 동일 유저의 peer 교체 // 재연결(WiFi→LTE 등) 시 동일 유저의 peer 교체
@@ -96,10 +147,54 @@ public class Channel
return -1; return -1;
} }
// 로비 가져옴 // 맵들 가져옴
public Robby GetRobby() public Dictionary<int, AMap> GetMaps()
{ {
return robby; return maps;
}
// 맵 가져옴
public AMap? GetMap(int mapId)
{
AMap? map = null;
maps.TryGetValue(mapId, out map);
return map;
}
// 사용 가능한 레이드 맵 ID 반환
// 기존 맵(1001~) 중 미사용 탐색 → 없으면 동적 생성 후 반환
public int GetOrCreateAvailableRaidMap()
{
// 기존 맵 중 미사용 탐색
foreach (int mapId in maps.Keys)
{
if (mapId >= 1001 && !useInstanceMaps.ContainsKey(mapId))
{
return mapId;
}
}
// 모두 사용 중 → 동적 생성
int newMapId = nextDynamicRaidMapId++;
BossInstance newMap = new(newMapId);
maps.Add(newMapId, newMap);
return newMapId;
}
// 레이드 맵 사용 시작 (진행중 목록에 등록)
public void AddInstanceMap(int mapId)
{
if (maps.TryGetValue(mapId, out AMap? map))
{
useInstanceMaps[mapId] = map;
}
}
// 레이드 맵 사용 종료 (진행중 목록에서 제거)
public void RemoveInstanceMap(int mapId)
{
useInstanceMaps.Remove(mapId);
} }
// 파티매니저 가져옴 // 파티매니저 가져옴
@@ -107,4 +202,6 @@ public class Channel
{ {
return partyManager; return partyManager;
} }
// TODO : 채널 가져오기
} }

View File

@@ -6,7 +6,11 @@ namespace MMOserver.Game.Channel;
public class ChannelManager : Singleton<ChannelManager> public class ChannelManager : Singleton<ChannelManager>
{ {
// 채널 관리 // 채널 관리
private List<Channel> channels = new List<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>();
@@ -18,9 +22,16 @@ public class ChannelManager : Singleton<ChannelManager>
public void Initializer(int channelSize = 1) public void Initializer(int channelSize = 1)
{ {
for (int i = 0; i <= channelSize; i++) for (int i = 1; i <= channelSize; i++)
{ {
channels.Add(new Channel(i)); channels.Add(i, new Channel(i));
}
// 보스 채널 생성
for (int i = 1; i <= bossChannelSize; i++)
{
int bossChannel = i + bossChannelStart;
channels.Add(bossChannel, new Channel(bossChannel));
} }
} }
@@ -29,15 +40,15 @@ public class ChannelManager : Singleton<ChannelManager>
return channels[channelId]; return channels[channelId];
} }
public List<Channel> GetChannels() public Dictionary<int, Channel> GetChannels()
{ {
return channels; return channels;
} }
public void AddUser(int channelId, int userId, Player player, NetPeer peer) public void AddUser(int channelId, int userId, Player player, NetPeer peer)
{ {
// 유저 추가 // 유저 추가 (채널 이동 시 기존 매핑 덮어쓰기 허용)
connectUsers.Add(userId, channelId); connectUsers[userId] = channelId;
// 채널에 유저 + peer 추가 // 채널에 유저 + peer 추가
channels[channelId].AddUser(userId, player, peer); channels[channelId].AddUser(userId, player, peer);
} }

View File

@@ -0,0 +1,24 @@
namespace MMOserver.Game.Channel.Maps;
public abstract class AMap
{
private Dictionary<int, Player> users = new Dictionary<int, Player>();
public abstract EnumMap GetMapType();
public abstract int GetMapId();
public void AddUser(int userId, Player player)
{
users[userId] = player;
}
public void RemoveUser(int userId)
{
users.Remove(userId);
}
public Dictionary<int, Player> GetUsers()
{
return users;
}
}

View File

@@ -0,0 +1,8 @@
namespace MMOserver.Game.Channel.Maps;
public enum EnumMap : int
{
NONE = 0,
ROBBY = 1,
INSTANCE = 10,
}

View File

@@ -0,0 +1,34 @@
using MMOserver.Game.Channel.Maps;
using MMOserver.Game.Engine;
namespace MMOserver.Game.Channel.Maps.InstanceDungeun;
// 인스턴스 보스 맵에 들어갈때 쓰는 것
public class BossInstance : AMap
{
private EnumMap enumMap;
private int mapId;
// 마을 시작 지점 넣어 둔다.
public static Vector3 StartPosition
{
get;
set;
} = new Vector3(0, 0, 0);
public BossInstance(int mapId, EnumMap enumMap = EnumMap.INSTANCE)
{
this.enumMap = enumMap;
this.mapId = mapId;
}
public override EnumMap GetMapType()
{
return enumMap;
}
public override int GetMapId()
{
return mapId;
}
}

View File

@@ -2,8 +2,11 @@
namespace MMOserver.Game.Channel.Maps; namespace MMOserver.Game.Channel.Maps;
public class Robby public class Robby : AMap
{ {
private EnumMap enumMap;
private int mapId;
// 마을 시작 지점 넣어 둔다. // 마을 시작 지점 넣어 둔다.
public static Vector3 StartPosition public static Vector3 StartPosition
{ {
@@ -11,7 +14,19 @@ public class Robby
set; set;
} = new Vector3(0, 0, 0); } = new Vector3(0, 0, 0);
public Robby() public Robby(int mapId, EnumMap enumMap = EnumMap.ROBBY)
{ {
this.enumMap = enumMap;
this.mapId = mapId;
}
public override EnumMap GetMapType()
{
return enumMap;
}
public override int GetMapId()
{
return mapId;
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -32,4 +32,21 @@ public class PartyInfo
{ {
return PartyMemberIds.Count; return PartyMemberIds.Count;
} }
public void DeepCopy(PartyInfo other)
{
this.PartyId = other.PartyId;
this.PartyName = other.PartyName;
this.LeaderId = other.LeaderId;
this.PartyMemberIds.Clear();
this.PartyMemberIds.AddRange(other.PartyMemberIds);
}
public void DeepCopySemi(PartyInfo other)
{
this.PartyId = other.PartyId;
this.PartyName = other.PartyName;
this.LeaderId = other.LeaderId;
this.PartyMemberIds = new List<int>();
}
} }

View File

@@ -13,26 +13,42 @@ public class PartyManager
private readonly Dictionary<int, int> playerPartyMap = new(); private readonly Dictionary<int, int> playerPartyMap = new();
// 파티 생성 // 파티 생성
public bool CreateParty(int leaderId, string partyName, out PartyInfo? party) public bool CreateParty(int leaderId, string partyName, out PartyInfo? party, List<int>? memeberIds = null)
{ {
party = null;
if (playerPartyMap.ContainsKey(leaderId)) if (playerPartyMap.ContainsKey(leaderId))
{ {
party = null;
return false; // 이미 파티에 속해있음 return false; // 이미 파티에 속해있음
} }
int partyId = partyUuidGenerator.Create(); int partyId = partyUuidGenerator.Create();
if (memeberIds == null)
{
memeberIds = new List<int>();
}
// 리더 중복 방지: 기존 멤버 목록에 리더가 없을 때만 추가
if (!memeberIds.Contains(leaderId))
{
memeberIds.Add(leaderId);
}
party = new PartyInfo party = new PartyInfo
{ {
PartyId = partyId, PartyId = partyId,
LeaderId = leaderId, LeaderId = leaderId,
PartyName = partyName, PartyName = partyName,
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;
} }
@@ -86,7 +102,8 @@ public class PartyManager
if (party.PartyMemberIds.Count == 0) if (party.PartyMemberIds.Count == 0)
{ {
DeletePartyInternal(partyId, party); DeletePartyInternal(partyId, party);
party = null; // id가 필요하다 그래서 참조해 둔다.
// party = null;
return true; return true;
} }
@@ -119,6 +136,27 @@ public class PartyManager
return true; return true;
} }
// 파티 업데이트
public bool UpdateParty(int leaderId, int partyId, string newPartyName, out PartyInfo? party)
{
party = null;
if (!parties.TryGetValue(partyId, out party))
{
return false;
}
if (party.LeaderId != leaderId)
{
party = null;
return false; // 리더만 업데이트 가능
}
// 파티 이름 변경
party.PartyName = newPartyName;
return true;
}
// 전체 파티 목록 조회 // 전체 파티 목록 조회
public IEnumerable<PartyInfo> GetAllParties() public IEnumerable<PartyInfo> GetAllParties()
{ {

View File

@@ -74,4 +74,18 @@ public class Player
get; get;
set; set;
} }
// 현재 위치한 맵 ID
public int CurrentMapId
{
get;
set;
}
// 레이드 입장 전 이전 맵 ID (레이드 종료 후 복귀용, 서버 캐싱)
public int PreviousMapId
{
get;
set;
}
} }

View File

@@ -114,6 +114,41 @@ public class PlayerInfo
get; get;
set; set;
} }
[ProtoMember(10)]
public int Experience
{
get;
set;
}
[ProtoMember(11)]
public int NextExp
{
get;
set;
}
[ProtoMember(12)]
public float AttackPower
{
get;
set;
}
[ProtoMember(13)]
public float AttackRange
{
get;
set;
}
[ProtoMember(14)]
public float SprintMultiplier
{
get;
set;
}
} }
// ============================================================ // ============================================================
@@ -163,7 +198,7 @@ public class LoadGamePacket
} }
[ProtoMember(3)] [ProtoMember(3)]
public int MaplId public int MapId
{ {
get; get;
set; set;
@@ -234,6 +269,13 @@ public class PartyInfoData
get; get;
set; set;
} = new List<int>(); } = new List<int>();
[ProtoMember(4)]
public string PartyName
{
get;
set;
}
} }
// INTO_CHANNEL 클라->서버: 입장할 채널 ID / 서버->클라: 채널 내 나 이외 플레이어 목록 // INTO_CHANNEL 클라->서버: 입장할 채널 ID / 서버->클라: 채널 내 나 이외 플레이어 목록
@@ -262,6 +304,40 @@ public class IntoChannelPacket
} = new List<PartyInfoData>(); // 서버->클라: 채널 내 파티 목록 } = new List<PartyInfoData>(); // 서버->클라: 채널 내 파티 목록
} }
// 파티원 모두 채널이동
// 클라->서버: 입장할 채널 ID
[ProtoContract]
public class IntoChannelPartyPacket
{
[ProtoMember(1)]
public int ChannelId
{
get;
set;
} // 클라->서버: 입장할 채널 ID
[ProtoMember(2)]
public List<PlayerInfo> Players
{
get;
set;
} = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록
[ProtoMember(3)]
public List<PartyInfoData> Parties
{
get;
set;
} = new List<PartyInfoData>(); // 서버->클라: 채널 내 파티 목록
[ProtoMember(4)]
public int PartyId
{
get;
set;
}
}
// UPDATE_CHANNEL_USER 유저 접속/나감 // UPDATE_CHANNEL_USER 유저 접속/나감
[ProtoContract] [ProtoContract]
public class UpdateChannelUserPacket public class UpdateChannelUserPacket
@@ -557,9 +633,10 @@ public enum ErrorCode : int
{ {
// 파티 (10021~) // 파티 (10021~)
PARTY_ALREADY_IN_PARTY = 10021, PARTY_ALREADY_IN_PARTY = 10021,
PARTY_JOIN_FAILED = 10022, PARTY_JOIN_FAILED = 10022,
PARTY_NOT_IN_PARTY = 10023, PARTY_NOT_IN_PARTY = 10023,
PARTY_DELETE_FAILED = 10024, PARTY_DELETE_FAILED = 10024,
PARTY_UPDATE_FAILED = 10025,
} }
// ERROR (서버 -> 클라) // ERROR (서버 -> 클라)
@@ -583,7 +660,8 @@ public enum PartyUpdateType
CREATE, CREATE,
DELETE, DELETE,
JOIN, JOIN,
LEAVE LEAVE,
UPDATE
} }
// REQUEST_PARTY (클라 -> 서버) - CREATE: PartyName 사용 / JOIN·LEAVE·DELETE: PartyId 사용 // REQUEST_PARTY (클라 -> 서버) - CREATE: PartyName 사용 / JOIN·LEAVE·DELETE: PartyId 사용
@@ -618,9 +696,9 @@ public class RequestPartyPacket
public enum ChatType public enum ChatType
{ {
GLOBAL, // 전체 채널 GLOBAL, // 전체 채널
PARTY, // 파티원 PARTY, // 파티원
WHISPER // 귓말 WHISPER // 귓말
} }
// CHAT (클라 -> 서버 & 서버 -> 클라) // CHAT (클라 -> 서버 & 서버 -> 클라)
@@ -664,6 +742,103 @@ public class ChatPacket
set; set;
} }
} }
// ============================================================
// 맵 이동
// ============================================================
// CHANGE_MAP (클라 -> 서버 & 서버 -> 클라)
[ProtoContract]
public class ChangeMapPacket
{
[ProtoMember(1)]
public int MapId
{
get;
set;
}
// 새 맵의 기존 플레이어 목록 (이동한 본인에게 전달)
[ProtoMember(2)]
public List<PlayerInfo> Players
{
get;
set;
} = new List<PlayerInfo>();
// 입장(true) / 퇴장(false) - 기존 맵 플레이어들에게 전달
[ProtoMember(3)]
public bool IsAdd
{
get;
set;
}
// 이동한 플레이어 정보 - 기존 맵 플레이어들에게 전달
[ProtoMember(4)]
public PlayerInfo Player
{
get;
set;
}
}
// INTO_BOSS_RAID
// 클라->서버: RaidId
// 서버->클라: RaidId + IsSuccess (파티장에게 결과 전달)
// 성공 시 파티원 전체에게 CHANGE_MAP 추가 전송
[ProtoContract]
public class IntoBossRaidPacket
{
// 입장할 보스 레이드 맵 Id
[ProtoMember(1)]
public int RaidId
{
get;
set;
}
// 입장 성공 여부 (서버 -> 클라)
[ProtoMember(2)]
public bool IsSuccess
{
get;
set;
}
[ProtoMember(3)]
public string Token
{
get;
set;
}
[ProtoMember(4)]
public string Session
{
get;
set;
}
}
// PARTY_CHANGE_MAP (클라 -> 서버 전용)
[ProtoContract]
public class PartyChangeMapPacket
{
[ProtoMember(1)]
public int MapId
{
get;
set;
}
[ProtoMember(2)]
public int PartyId
{
get;
set;
}
}
// ============================================================ // ============================================================
// 파티 // 파티

View File

@@ -2,61 +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,
// 새로운 유저 채널 접속 (서버 -> 클라) / 유저 채널 나감 (서버 -> 클라)
UPDATE_CHANNEL_USER,
// 채널 나가기 (클라 -> 서버)
EXIT_CHANNEL,
// 플레이어 위치, 방향 (서버 -> 클라 \ 클라 -> 서버)
TRANSFORM_PLAYER,
// 플레이어 행동 업데이트 (서버 -> 클라 \ 클라 -> 서버)
ACTION_PLAYER,
// 플레이어 스테이트 업데이트 (서버 -> 클라 \ 클라 -> 서버)
STATE_PLAYER,
// NPC 위치, 방향 (서버 -> 클라)
TRANSFORM_NPC,
// NPC 행동 업데이트 (서버 -> 클라)
ACTION_NPC,
// NPC 스테이트 업데이트 (서버 -> 클라)
STATE_NPC,
// 데미지 UI 전달 (서버 -> 클라)
DAMAGE,
// 파티 생성/삭제, 파티원 추가/제거 (서버 -> 클라)
UPDATE_PARTY,
// 파티 참가/탈퇴/생성/해산 요청 (클라 -> 서버)
REQUEST_PARTY,
// 채팅 (클라 -> 서버 & 서버 -> 클라) - GLOBAL / PARTY / WHISPER
CHAT,
// 요청 실패 응답 (서버 -> 클라) // 요청 실패 응답 (서버 -> 클라)
ERROR = 9999 ERROR = 9999
} }

View File

@@ -1,4 +1,5 @@
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using MMOserver.Config;
using MMOserver.Game; using MMOserver.Game;
using MMOserver.RDB; using MMOserver.RDB;
using Serilog; using Serilog;
@@ -21,6 +22,8 @@ class Program
.AddEnvironmentVariables() // 도커 배포용 .AddEnvironmentVariables() // 도커 배포용
.Build(); .Build();
AppConfig.Initialize(config);
// DB 연결 // DB 연결
// DbConnectionFactory dbFactory = new DbConnectionFactory(config); // DbConnectionFactory dbFactory = new DbConnectionFactory(config);
@@ -34,7 +37,7 @@ class Program
Log.Information("Write Log Started"); Log.Information("Write Log Started");
int port = 9500; int port = AppConfig.Server.Port;
string connectionString = "test"; string connectionString = "test";
GameServer gameServer = new GameServer(port, connectionString); GameServer gameServer = new GameServer(port, connectionString);

View File

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

View File

@@ -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
{ {
@@ -118,26 +121,29 @@ public abstract class ServerBase : INetEventListener
// 클라이언트가 연결 해제됐을 때 (타임아웃, 명시적 끊기 등) // 클라이언트가 연결 해제됐을 때 (타임아웃, 명시적 끊기 등)
public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo)
{ {
pendingPeers.Remove(peer.Id); lock (sessionLock)
if (peer.Tag is Session session)
{ {
// 현재 인증된 피어가 이 peer일 때만 세션 제거 pendingPeers.Remove(peer.Id);
// (재연결로 이미 교체된 경우엔 건드리지 않음)
if (sessions.TryGetValue(session.HashKey, out NetPeer? current) && current.Id == peer.Id) if (peer.Tag is Session session)
{ {
// 더미 클라 아니면 token관리 // 현재 인증된 피어가 이 peer일 때만 세션 제거
if (!string.IsNullOrEmpty(session.Token)) // (재연결로 이미 교체된 경우엔 건드리지 않음)
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); peer.Tag = null;
Log.Information("[Server] 세션 해제 HashKey={Key} Reason={Reason}", session.HashKey, disconnectInfo.Reason);
OnSessionDisconnected(peer, session.HashKey, disconnectInfo);
} }
peer.Tag = null;
} }
} }
@@ -167,7 +173,11 @@ 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) else if (type == (ushort)PacketType.DUMMY_ACC_TOKEN)
@@ -240,7 +250,7 @@ public abstract class ServerBase : INetEventListener
// ─── Auth 처리 ──────────────────────────────────────────────── // ─── Auth 처리 ────────────────────────────────────────────────
protected abstract void HandleAuth(NetPeer peer, byte[] payload); protected abstract Task HandleAuth(NetPeer peer, byte[] payload);
// ─── 전송 헬퍼 ─────────────────────────────────────────────────────── // ─── 전송 헬퍼 ───────────────────────────────────────────────────────

View File

@@ -16,25 +16,29 @@ public class Session
init; init;
} }
public string UserName
{
get;
set;
}
public NetPeer Peer public NetPeer Peer
{ {
get; get;
set; set;
} }
// ─── 패킷 레이트 리미팅 ─────────────────────────── // 패킷 레이트 리미팅
private int packetCount; private int packetCount;
private long windowStartTicks; private long windowStartTicks;
/// <summary>초당 허용 패킷 수</summary> // 초당 허용 패킷 수
public int MaxPacketsPerSecond { get; set; } public int MaxPacketsPerSecond { get; set; }
/// <summary>연속 초과 횟수</summary> // 연속 초과 횟수
public int RateLimitViolations { get; private set; } public int RateLimitViolations { get; private set; }
/// <summary> // 패킷 수신 시 호출. 초당 제한 초과 시 true 반환.
/// 패킷 수신 시 호출. 초당 제한 초과 시 true 반환.
/// </summary>
public bool CheckRateLimit() public bool CheckRateLimit()
{ {
long now = Environment.TickCount64; long now = Environment.TickCount64;
@@ -57,7 +61,7 @@ public class Session
return false; return false;
} }
/// <summary>위반 카운트 초기화</summary> // 위반 카운트 초기화
public void ResetViolations() public void ResetViolations()
{ {
RateLimitViolations = 0; RateLimitViolations = 0;

View File

@@ -7,6 +7,16 @@
ports: ports:
- "9050:9050/udp" # LiteNetLib UDP 포트 - "9050:9050/udp" # LiteNetLib UDP 포트
- "9500:9500/udp" # LiteNetLib UDP 포트 - "9500:9500/udp" # LiteNetLib UDP 포트
- "40001:9500/udp" # LiteNetLib UDP 포트
- "40002:9500/udp" # LiteNetLib UDP 포트
- "40003:9500/udp" # LiteNetLib UDP 포트
- "40004:9500/udp" # LiteNetLib UDP 포트
- "40005:9500/udp" # LiteNetLib UDP 포트
- "40006:9500/udp" # LiteNetLib UDP 포트
- "40007:9500/udp" # LiteNetLib UDP 포트
- "40008:9500/udp" # LiteNetLib UDP 포트
- "40009:9500/udp" # LiteNetLib UDP 포트
- "40100:9500/udp" # LiteNetLib UDP 포트
environment: environment:
- DOTNET_DbgEnableMiniDump=1 # 크래시 시 덤프 자동 생성 - DOTNET_DbgEnableMiniDump=1 # 크래시 시 덤프 자동 생성
- DOTNET_DbgMiniDumpType=4 # 4 = Full dump - DOTNET_DbgMiniDumpType=4 # 4 = Full dump