21 Commits

Author SHA1 Message Date
a5eedb2fb2 fix: 크로스 프로젝트 통신 버그 수정
- Tokens 타입 string? → Dictionary<string,string>? (Go API JSON object 역직렬화 실패 수정)
- 409 응답 핸들러 return false → return null (컴파일 에러 수정)
- INTO_BOSS_RAID 파티원 각자에게 본인 토큰과 함께 전달 (기존: 파티장에게 N번 중복)
- GetPlayer null 체크 추가 (NullReferenceException 방지)
- BossId 하드코딩 1 → packet.RaidId 사용
- Player 클래스에 Experience/AttackPower 등 전투 스탯 필드 추가
- ToPlayerInfo에서 새 필드 매핑 추가
- OnIntoChannelParty Nickname을 Session.UserName에서 가져오도록 수정

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 00:20:20 +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
qornwh1
1487082cc6 fix : 도커 의존성 추가, 윈도우용 미니덤프 제거 Dotnet-dump사용 2026-03-11 12:55:24 +09:00
qornwh1
9828b967a1 feat : 파티 패킷 추가 / 채널 접속시 모든 파티 리스트 전달 2026-03-10 09:40:00 +09:00
qornwh1
a3bcbd073e fix : 덤프 남길때 현재 콜스택 저장 기능 추가 2026-03-10 09:03:46 +09:00
30 changed files with 1603 additions and 246 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -144,15 +144,15 @@ public class StressTestClient
posX = nextX;
posZ = nextZ;
distance = hitWall ? 0f : distance - step;
position.X = (int)MathF.Round(posX);
position.Z = (int)MathF.Round(posZ);
position.X = posX;
position.Z = posZ;
// 전송
TransformPlayerPacket pkt = new TransformPlayerPacket
{
PlayerId = clientId,
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);
writer.Put(data);

View File

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

View File

@@ -0,0 +1,6 @@
{
"ServerIp": "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; } = new();
}

View File

@@ -1,6 +1,7 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using MMOserver.Config;
using MMOserver.Utils;
using Serilog;
@@ -8,28 +9,33 @@ namespace MMOserver.Api;
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 const int MAX_RETRY = 3;
private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(1);
public RestApi()
{
httpClient.DefaultRequestHeaders.Add("X-API-Key", AppConfig.RestApi.ApiKey);
}
// 토큰 검증 - 성공 시 username 반환
// 401 → 재시도 없이 즉시 null 반환 (토큰 자체가 무효)
// 타임아웃/네트워크 오류 → 최대 MAX_RETRY회 재시도 후 null 반환
public async Task<string?> VerifyTokenAsync(string token)
{
string url = AppConfig.RestApi.BaseUrl + AppConfig.RestApi.VerifyToken;
for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
{
try
{
HttpResponseMessage response = await httpClient.PostAsJsonAsync(VERIFY_URL, new { token });
HttpResponseMessage response = await httpClient.PostAsJsonAsync(url, new { token });
// 401: 토큰 자체가 무효 → 재시도해도 같은 결과, 즉시 반환
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Log.Warning("[RestApi] 토큰 인증 실패 (401)");
return null;
return "";
}
response.EnsureSuccessStatusCode();
@@ -50,7 +56,7 @@ public class RestApi : Singleton<RestApi>
}
}
return null;
return "";
}
private sealed class AuthVerifyResponse
@@ -62,4 +68,115 @@ public class RestApi : Singleton<RestApi>
set;
}
}
// 레이드 채널 접속 여부 체크
// 성공 시 BossRaidResult 반환, 실패/거절 시 null 반환
public async Task<BossRaidResult?> BossRaidAccesssAsync(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: 입장 조건 미충족 (레벨 부족 등)
if (response.StatusCode == HttpStatusCode.BadRequest)
{
Log.Warning("[RestApi] 보스 레이드 입장 거절 (400) BossId={BossId}", bossId);
return null;
}
// 409: 이미 진행 중이거나 슬롯 충돌
if (response.StatusCode == HttpStatusCode.Conflict)
{
Log.Warning("[RestApi] 보스 레이드 충돌 (409) BossId={BossId} - 이미 진행 중이거나 슬롯 없음", 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 ?? new()
};
}
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

@@ -5,7 +5,9 @@ WORKDIR /app
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
# ServerLib 의존성 포함해서 restore (캐시 레이어 최적화)
COPY ["MMOserver/MMOserver.csproj", "MMOserver/"]
COPY ["ServerLib/ServerLib.csproj", "ServerLib/"]
RUN dotnet restore "MMOserver/MMOserver.csproj"
COPY . .
WORKDIR "/src/MMOserver"

View File

@@ -1,27 +1,51 @@
using LiteNetLib;
using MMOserver.Game.Channel.Maps;
using MMOserver.Game.Channel.Maps.InstanceDungeun;
using MMOserver.Game.Party;
namespace MMOserver.Game.Channel;
public class Channel
{
// 로비
private Robby robby = new Robby();
// 파티
private PartyManager partyManager = new PartyManager();
// 채널 내 유저 NetPeer (hashKey → NetPeer) — BroadcastToChannel 교차 조회 제거용
private readonly Dictionary<int, NetPeer> connectPeers = new();
// 채널 내 유저 상태 (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
{
get;
private set;
}
public int UserCount
@@ -36,25 +60,49 @@ public class Channel
private set;
} = 100;
public Channel(int channelId)
{
ChannelId = channelId;
}
public void AddUser(int userId, Player player, NetPeer peer)
{
connectUsers[userId] = player;
connectPeers[userId] = peer;
UserCount++;
// 처음 접속 시 1번 맵(로비)으로 입장
ChangeMap(userId, player, 1);
}
public void RemoveUser(int userId)
{
// 현재 맵에서도 제거
if (connectUsers.TryGetValue(userId, out Player? player) &&
maps.TryGetValue(player.CurrentMapId, out AMap? currentMap))
{
currentMap.RemoveUser(userId);
}
connectUsers.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 교체
public void UpdatePeer(int userId, NetPeer peer)
{
@@ -96,10 +144,54 @@ public class Channel
return -1;
}
// 로비 가져옴
public Robby GetRobby()
// 맵들 가져옴
public Dictionary<int, AMap> GetMaps()
{
return robby;
return maps;
}
// 맵 가져옴
public AMap? GetMap(int mapId)
{
AMap? map = null;
maps.TryGetValue(mapId, out map);
return map;
}
// 사용 가능한 레이드 맵 ID 반환
// 기존 맵(1001~) 중 미사용 탐색 → 없으면 동적 생성 후 반환
public int GetOrCreateAvailableRaidMap()
{
// 기존 맵 중 미사용 탐색
foreach (int mapId in maps.Keys)
{
if (mapId >= 1001 && !useInstanceMaps.ContainsKey(mapId))
{
return mapId;
}
}
// 모두 사용 중 → 동적 생성
int newMapId = nextDynamicRaidMapId++;
BossInstance newMap = new(newMapId);
maps.Add(newMapId, newMap);
return newMapId;
}
// 레이드 맵 사용 시작 (진행중 목록에 등록)
public void AddInstanceMap(int mapId)
{
if (maps.TryGetValue(mapId, out AMap? map))
{
useInstanceMaps[mapId] = map;
}
}
// 레이드 맵 사용 종료 (진행중 목록에서 제거)
public void RemoveInstanceMap(int mapId)
{
useInstanceMaps.Remove(mapId);
}
// 파티매니저 가져옴
@@ -107,4 +199,6 @@ public class Channel
{
return partyManager;
}
// TODO : 채널 가져오기
}

View File

@@ -6,7 +6,11 @@ namespace MMOserver.Game.Channel;
public class ChannelManager : Singleton<ChannelManager>
{
// 채널 관리
private List<Channel> channels = new List<Channel>();
private Dictionary<int, Channel> channels = new Dictionary<int, Channel>();
// 보스 레이드 채널
private readonly int bossChannelStart = 10000;
private readonly int bossChannelSize = 10;
// 채널별 유저 관리 (유저 key, 채널 val)
private Dictionary<int, int> connectUsers = new Dictionary<int, int>();
@@ -18,9 +22,16 @@ public class ChannelManager : Singleton<ChannelManager>
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];
}
public List<Channel> GetChannels()
public Dictionary<int, Channel> GetChannels()
{
return channels;
}
public void AddUser(int channelId, int userId, Player player, NetPeer peer)
{
// 유저 추가
connectUsers.Add(userId, channelId);
// 유저 추가 (채널 이동 시 기존 매핑 덮어쓰기 허용)
connectUsers[userId] = channelId;
// 채널에 유저 + 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;
public class Robby
public class Robby : AMap
{
private EnumMap enumMap;
private int mapId;
// 마을 시작 지점 넣어 둔다.
public static Vector3 StartPosition
{
@@ -11,7 +14,19 @@ public class Robby
set;
} = 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;
}
}

View File

@@ -2,6 +2,7 @@ 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;
@@ -15,19 +16,23 @@ namespace MMOserver.Game;
public class GameServer : ServerBase
{
private readonly Dictionary<ushort, Action<NetPeer, int, byte[]>> packetHandlers;
private UuidGenerator userUuidGenerator;
private readonly UuidGenerator userUuidGenerator;
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,
[(ushort)PacketCode.CHAT] = OnChat
};
userUuidGenerator = new UuidGenerator();
}
@@ -41,7 +46,7 @@ public class GameServer : ServerBase
}
// 세션에 넣지는 않는다.
NetDataReader reader = new NetDataReader(payload);
NetDataReader reader = new(payload);
short code = reader.GetShort();
short bodyLength = reader.GetShort();
@@ -73,11 +78,12 @@ public class GameServer : ServerBase
{
// 더미 클라다.
ChannelManager cm = ChannelManager.Instance;
Player newPlayer = new Player
Player newPlayer = new()
{
HashKey = hashKey,
PlayerId = hashKey,
Nickname = hashKey.ToString()
Nickname = hashKey.ToString(),
CurrentMapId = 1
};
cm.AddUser(1, hashKey, newPlayer, peer);
@@ -97,6 +103,7 @@ public class GameServer : ServerBase
{
AccTokenPacket accTokenPacket = Serializer.Deserialize<AccTokenPacket>(new ReadOnlyMemory<byte>(payload));
string token = accTokenPacket.Token;
string username = "";
tokenHash.TryGetValue(token, out int hashKey);
if (hashKey <= 1000)
{
@@ -114,7 +121,7 @@ public class GameServer : ServerBase
else
{
// 신규 연결: 웹서버에 JWT 검증 요청
string? username = await RestApi.Instance.VerifyTokenAsync(token);
username = await RestApi.Instance.VerifyTokenAsync(token);
if (username == null)
{
Log.Warning("[Server] 토큰 검증 실패 - 연결 거부 PeerId={Id}", peer.Id);
@@ -128,6 +135,11 @@ public class GameServer : ServerBase
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);
@@ -169,9 +181,12 @@ public class GameServer : ServerBase
{
Log.Information("[GameServer] 세션 해제 HashKey={Key} Reason={Reason}", hashKey, info.Reason);
// 같은 채널 유저들에게 나갔다고 알림
if (channelId >= 0 && player != null)
{
// 파티 자동 탈퇴
HandlePartyLeaveOnExit(channelId, hashKey);
// 같은 채널 유저들에게 나갔다고 알림
SendExitChannelPacket(peer, hashKey, channelId, player);
}
}
@@ -204,34 +219,39 @@ public class GameServer : ServerBase
private void SendLoadChannelPacket(NetPeer peer, int hashKey)
{
LoadChannelPacket loadChannelPacket = new LoadChannelPacket();
foreach (Channel.Channel channel in ChannelManager.Instance.GetChannels())
LoadChannelPacket loadChannelPacket = new();
foreach (Channel.Channel channel in ChannelManager.Instance.GetChannels().Values)
{
if (channel.ChannelId <= 0)
{
continue;
}
ChannelInfo info = new ChannelInfo();
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<LoadChannelPacket>((ushort)PacketCode.LOAD_CHANNEL, loadChannelPacket);
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 UpdateChannelUserPacket
UpdateChannelUserPacket packet = new()
{
Players = ToPlayerInfo(player),
IsAdd = false
};
byte[] data = PacketSerializer.Serialize<UpdateChannelUserPacket>((ushort)PacketCode.UPDATE_CHANNEL_USER, packet);
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_CHANNEL_USER, packet);
// 이미 채널에서 제거된 후라 나간 본인에게는 전송되지 않음
BroadcastToChannel(channelId, data);
}
@@ -251,8 +271,8 @@ public class GameServer : ServerBase
Channel.Channel channel = cm.GetChannel(channelId);
Player? myPlayer = channel.GetPlayer(hashKey);
// 1. 새 유저에게: 자신을 제외한 기존 채널 유저 목록 전송
IntoChannelPacket response = new IntoChannelPacket { ChannelId = channelId };
// 1. 새 유저에게: 자신을 제외한 기존 채널 유저 목록 + 파티 목록 전송
IntoChannelPacket response = new() { ChannelId = channelId };
foreach (int userId in channel.GetConnectUsers())
{
if (userId == hashKey)
@@ -267,18 +287,29 @@ public class GameServer : ServerBase
}
}
byte[] toNewUser = PacketSerializer.Serialize<IntoChannelPacket>((ushort)PacketCode.INTO_CHANNEL, response);
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 UpdateChannelUserPacket
UpdateChannelUserPacket notify = new()
{
Players = ToPlayerInfo(myPlayer),
IsAdd = true
};
byte[] toOthers = PacketSerializer.Serialize<UpdateChannelUserPacket>((ushort)PacketCode.UPDATE_CHANNEL_USER, notify);
byte[] toOthers = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_CHANNEL_USER, notify);
BroadcastToChannel(channelId, toOthers, peer);
}
}
@@ -294,19 +325,20 @@ public class GameServer : ServerBase
if (player == null)
{
Log.Warning("[GameServer] LOAD_GAME 플레이어 없음 HashKey={Key}", hashKey);
byte[] denied = PacketSerializer.Serialize<LoadGamePacket>((ushort)PacketCode.LOAD_GAME, new LoadGamePacket { IsAccepted = false });
byte[] denied =
PacketSerializer.Serialize((ushort)PacketCode.LOAD_GAME, new LoadGamePacket { IsAccepted = false });
SendTo(peer, denied);
return;
}
LoadGamePacket packet = new LoadGamePacket
LoadGamePacket packet = new()
{
IsAccepted = true,
Player = ToPlayerInfo(player),
MaplId = channelId,
MaplId = channelId
};
byte[] data = PacketSerializer.Serialize<LoadGamePacket>((ushort)PacketCode.LOAD_GAME, packet);
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);
}
@@ -317,7 +349,8 @@ public class GameServer : ServerBase
// 특정 채널의 모든 유저에게 전송 (exclude 지정 시 해당 피어 제외)
// Channel이 NetPeer를 직접 보유하므로 sessions 교차 조회 없음
private void BroadcastToChannel(int channelId, byte[] data, NetPeer? exclude = null, DeliveryMethod method = DeliveryMethod.ReliableOrdered)
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())
@@ -331,6 +364,32 @@ public class GameServer : ServerBase
}
}
// 특정 맵의 유저들에게 전송 (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);
}
}
// ============================================================
// Player ↔ PlayerInfo 변환 (패킷 전송 시에만 사용)
// ============================================================
@@ -348,6 +407,11 @@ public class GameServer : ServerBase
MaxMp = player.MaxMp,
Position = new Position { X = player.PosX, Y = player.PosY, Z = player.PosZ },
RotY = player.RotY,
Experience = player.Experience,
NextExp = player.NextExp,
AttackPower = player.AttackPower,
AttackRange = player.AttackRange,
SprintMultiplier = player.SprintMultiplier
};
}
@@ -360,26 +424,49 @@ public class GameServer : ServerBase
IntoChannelPacket packet = Serializer.Deserialize<IntoChannelPacket>(new ReadOnlyMemory<byte>(payload));
ChannelManager cm = ChannelManager.Instance;
Channel.Channel channel = cm.GetChannel(packet.ChannelId);
// 이전에 다른 채널에 있었는지 체크
int preChannelId = cm.HasUser(hashKey);
if (preChannelId >= 0)
{
// 제거 전에 채널/플레이어 정보 저장 (브로드캐스트에 필요)
Player? player = cm.GetChannel(preChannelId).GetPlayer(hashKey);
// 파티 자동 탈퇴
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 (channel.UserCount >= channel.UserCountMax)
if (newChannel.UserCount >= newChannel.UserCountMax)
{
Log.Warning("[GameServer] INTO_CHANNEL 채널 인원 초과 HashKey={Key} ChannelId={ChannelId} UserCount={Count}/{Max}",
hashKey, packet.ChannelId, channel.UserCount, channel.UserCountMax);
byte[] full = PacketSerializer.Serialize<IntoChannelPacket>((ushort)PacketCode.INTO_CHANNEL, new IntoChannelPacket { ChannelId = -1 });
hashKey, packet.ChannelId, newChannel.UserCount, newChannel.UserCountMax);
byte[] full = PacketSerializer.Serialize((ushort)PacketCode.INTO_CHANNEL,
new IntoChannelPacket { ChannelId = -1 });
SendTo(peer, full);
return;
}
// TODO: 실제 서비스에서는 DB/세션에서 플레이어 정보 로드 필요
Player newPlayer = new Player
Player newPlayer = new()
{
HashKey = hashKey,
PlayerId = hashKey,
Nickname = hashKey.ToString()
Nickname = ((Session)peer.Tag).UserName
};
// 채널에 추가
cm.AddUser(packet.ChannelId, hashKey, newPlayer, peer);
Log.Debug("[GameServer] INTO_CHANNEL HashKey={Key} ChannelId={ChannelId}", hashKey, packet.ChannelId);
@@ -388,6 +475,152 @@ public class GameServer : ServerBase
// 내 정보 전달
SendLoadGame(peer, hashKey);
// 초기 맵(로비 1번) 진입 알림
// Channel.AddUser → ChangeMap(1) 에서 이미 맵에 추가됨
PlayerInfo playerInfo = ToPlayerInfo(newPlayer);
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, p) in initMap.GetUsers())
{
if (userId == hashKey)
{
continue;
}
response.Players.Add(ToPlayerInfo(p));
}
}
SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
}
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);
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)
{
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;
}
// 기존 채널에서 제거 + 기존 채널 유저들에게 나감 알림
foreach (int memberId in preParty.PartyMemberIds)
{
Player? player = preChannel.GetPlayer(memberId);
if (player != null)
{
UpdateChannelUserPacket exitNotify = new()
{
Players = ToPlayerInfo(player),
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)
{
// 세션에서 username 조회
string nickname = memberPeer.Tag is Session s && !string.IsNullOrEmpty(s.UserName)
? s.UserName
: 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] 파티생성 실패 !!!");
}
}
private void OnExitChannel(NetPeer peer, int hashKey, byte[] payload)
@@ -400,6 +633,12 @@ public class GameServer : ServerBase
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);
@@ -423,17 +662,19 @@ public class GameServer : ServerBase
// 채널 내 플레이어 위치/방향 상태 갱신
Player? player = cm.GetChannel(channelId).GetPlayer(hashKey);
if (player != null)
if (player == null)
{
player.PosX = packet.Position.X;
player.PosY = packet.Position.Y;
player.PosZ = packet.Position.Z;
player.RotY = packet.RotY;
return;
}
// 같은 채널 유저들에게 위치/방향 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize<TransformPlayerPacket>((ushort)PacketCode.TRANSFORM_PLAYER, packet);
BroadcastToChannel(channelId, data, peer, DeliveryMethod.Unreliable);
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);
}
private void OnActionPlayer(NetPeer peer, int hashKey, byte[] payload)
@@ -447,9 +688,15 @@ public class GameServer : ServerBase
return;
}
// 같은 채널 유저들에게 행동 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize<ActionPlayerPacket>((ushort)PacketCode.ACTION_PLAYER, packet);
BroadcastToChannel(channelId, data, peer);
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);
}
private void OnStatePlayer(NetPeer peer, int hashKey, byte[] payload)
@@ -465,17 +712,19 @@ public class GameServer : ServerBase
// 채널 내 플레이어 HP/MP 상태 갱신
Player? player = cm.GetChannel(channelId).GetPlayer(hashKey);
if (player != null)
if (player == null)
{
player.Hp = packet.Hp;
player.MaxHp = packet.MaxHp;
player.Mp = packet.Mp;
player.MaxMp = packet.MaxMp;
return;
}
// 같은 채널 유저들에게 스테이트 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize<StatePlayerPacket>((ushort)PacketCode.STATE_PLAYER, packet);
BroadcastToChannel(channelId, data, peer);
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);
}
private void OnRequestParty(NetPeer peer, int hashKey, byte[] payload)
@@ -501,16 +750,16 @@ public class GameServer : ServerBase
return;
}
UpdatePartyPacket notify = new UpdatePartyPacket
UpdatePartyPacket notify = new()
{
PartyId = party!.PartyId,
Type = PartyUpdateType.CREATE,
LeaderId = party.LeaderId,
PlayerId = hashKey,
PartyName = party.PartyName,
PartyName = party.PartyName
};
byte[] data = PacketSerializer.Serialize<UpdatePartyPacket>((ushort)PacketCode.UPDATE_PARTY, notify);
SendTo(peer, data);
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, notify);
BroadcastToChannel(channelId, data); // 채널 전체 파티 목록 갱신
break;
}
case PartyUpdateType.JOIN:
@@ -521,39 +770,38 @@ public class GameServer : ServerBase
return;
}
UpdatePartyPacket notify = new UpdatePartyPacket
UpdatePartyPacket notify = new()
{
PartyId = party!.PartyId,
Type = PartyUpdateType.JOIN,
LeaderId = party.LeaderId,
PlayerId = hashKey,
PlayerId = hashKey
};
byte[] data = PacketSerializer.Serialize<UpdatePartyPacket>((ushort)PacketCode.UPDATE_PARTY, notify);
BroadcastToUsers(party.PartyMemberIds, data); // 새 멤버 포함 전원
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, notify);
BroadcastToChannel(channelId, data); // 채널 전체 파티 목록 갱신
break;
}
case PartyUpdateType.LEAVE:
{
if (!pm.LeaveParty(hashKey, out PartyInfo? party))
if (!pm.LeaveParty(hashKey, out PartyInfo? party) || party == null)
{
SendError(peer, ErrorCode.PARTY_NOT_IN_PARTY);
return;
}
UpdatePartyPacket notify = new UpdatePartyPacket
UpdatePartyPacket notify = new()
{
PartyId = req.PartyId,
Type = PartyUpdateType.LEAVE,
LeaderId = party?.LeaderId ?? 0,
PlayerId = hashKey,
PartyId = party.PartyId, Type = PartyUpdateType.DELETE, LeaderId = party.LeaderId, PlayerId = hashKey
};
byte[] data = PacketSerializer.Serialize<UpdatePartyPacket>((ushort)PacketCode.UPDATE_PARTY, notify);
if (party != null)
// 파티가 남아있으면 살린다.
if (party.PartyMemberIds.Count > 0)
{
BroadcastToUsers(party.PartyMemberIds, data); // 남은 멤버들에게
notify.Type = PartyUpdateType.LEAVE;
}
SendTo(peer, data); // 탈퇴자 본인에게
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.UPDATE_PARTY, notify);
BroadcastToChannel(channelId, data); // 채널 전체 파티 목록 갱신 (탈퇴자 포함)
break;
}
case PartyUpdateType.DELETE:
@@ -564,14 +812,34 @@ public class GameServer : ServerBase
return;
}
UpdatePartyPacket notify = new UpdatePartyPacket
UpdatePartyPacket notify = new()
{
PartyId = party!.PartyId,
Type = PartyUpdateType.DELETE,
LeaderId = party.LeaderId,
LeaderId = party.LeaderId
};
byte[] data = PacketSerializer.Serialize<UpdatePartyPacket>((ushort)PacketCode.UPDATE_PARTY, notify);
BroadcastToUsers(party.PartyMemberIds, data); // 전원 (리더 포함)
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;
}
}
@@ -595,16 +863,16 @@ public class GameServer : ServerBase
}
// 서버에서 발신자 정보 채워줌 (클라 위조 방지)
ChatPacket res = new ChatPacket
ChatPacket res = new()
{
Type = req.Type,
SenderId = sender.PlayerId,
SenderNickname = sender.Nickname,
TargetId = req.TargetId,
Message = req.Message,
Message = req.Message
};
byte[] data = PacketSerializer.Serialize<ChatPacket>((ushort)PacketCode.CHAT, res);
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.CHAT, res);
switch (req.Type)
{
@@ -646,10 +914,302 @@ public 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;
if (!channel.ChangeMap(hashKey, player, packet.MapId))
{
Log.Warning("[GameServer] CHANGE_MAP 유효하지 않은 맵 HashKey={Key} MapId={MapId}", hashKey, packet.MapId);
return;
}
PlayerInfo playerInfo = ToPlayerInfo(player);
// 기존 맵 유저들에게 퇴장 알림
ChangeMapPacket exitNotify = new() { MapId = oldMapId, IsAdd = false, Player = playerInfo };
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 response = new() { MapId = packet.MapId };
AMap? newMap = channel.GetMap(packet.MapId);
if (newMap != null)
{
foreach ((int uid, Player p) in newMap.GetUsers())
{
if (uid == hashKey)
{
continue;
}
response.Players.Add(ToPlayerInfo(p));
}
}
SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
Log.Debug("[GameServer] CHANGE_MAP HashKey={Key} OldMap={OldMapId} NewMap={MapId}", hashKey, oldMapId, packet.MapId);
}
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 = 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 = 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 p) in newMap.GetUsers())
{
if (uid == memberId)
{
continue;
}
response.Players.Add(ToPlayerInfo(p));
}
}
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);
}
private async void OnIntoBossRaid(NetPeer peer, int hashKey, byte[] payload)
{
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 }));
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 }));
return;
}
// API로 접속 체크
List<string> userNames = new List<string>();
foreach (int memberId in party.PartyMemberIds)
{
Player? member = channel.GetPlayer(memberId);
if (member == null)
{
continue;
}
userNames.Add(member.Nickname);
}
BossRaidResult? result = await RestApi.Instance.BossRaidAccesssAsync(userNames, packet.RaidId);
// 입장 실패
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)
{
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())
{
if (uid != memberId)
{
response.Players.Add(ToPlayerInfo(p));
}
}
}
SendTo(memberPeer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
// 각 파티원에게 레이드 입장 정보 전달 (본인의 토큰 포함)
string? memberToken = null;
result.Tokens?.TryGetValue(memberPlayer.Nickname, out memberToken);
SendTo(memberPeer,
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket
{ RaidId = assignedRaidMapId, IsSuccess = true, Session = result.SessionName, Token = memberToken }));
}
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId}", hashKey, party.PartyId,
assignedRaidMapId);
}
// 채널 퇴장/연결 해제 시 파티 자동 탈퇴 처리
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);
// 0명 → DELETE, 남은 멤버 있음 → LEAVE
UpdatePartyPacket notify = remaining != null
? 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 SendError(NetPeer peer, ErrorCode code)
{
ErrorPacket err = new ErrorPacket { Code = code };
byte[] data = PacketSerializer.Serialize<ErrorPacket>((ushort)PacketCode.ERROR, err);
ErrorPacket err = new() { Code = code };
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.ERROR, err);
SendTo(peer, data);
}

View File

@@ -32,4 +32,21 @@ public class PartyInfo
{
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,21 +13,27 @@ public class PartyManager
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))
{
party = null;
return false; // 이미 파티에 속해있음
}
int partyId = partyUuidGenerator.Create();
if (memeberIds == null)
{
memeberIds = new List<int>();
}
party = new PartyInfo
{
PartyId = partyId,
LeaderId = leaderId,
PartyName = partyName,
PartyMemberIds = memeberIds
};
party.PartyMemberIds.Add(leaderId);
@@ -86,7 +92,8 @@ public class PartyManager
if (party.PartyMemberIds.Count == 0)
{
DeletePartyInternal(partyId, party);
party = null;
// id가 필요하다 그래서 참조해 둔다.
// party = null;
return true;
}
@@ -119,6 +126,33 @@ public class PartyManager
return true;
}
// 파티 업데이트
public bool UpdateParty(int leaderId, int partyId, string newPartyName, out PartyInfo? party)
{
party = null;
if (!parties.TryGetValue(partyId, out party))
{
return false;
}
if (party.LeaderId != leaderId)
{
party = null;
return false; // 리더만 업데이트 가능
}
// 파티 이름 변경
party.PartyName = newPartyName;
return true;
}
// 전체 파티 목록 조회
public IEnumerable<PartyInfo> GetAllParties()
{
return parties.Values;
}
// 조회
public PartyInfo? GetParty(int partyId)
{

View File

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

View File

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

View File

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

@@ -21,12 +21,24 @@ public enum PacketCode : ushort
// 나 채널 접속 (클라 -> 서버)
INTO_CHANNEL,
// 파티 채널 접속 (클라 -> 서버)
INTO_CHANNEL_PARTY,
// 새로운 유저 채널 접속 (서버 -> 클라) / 유저 채널 나감 (서버 -> 클라)
UPDATE_CHANNEL_USER,
// 채널 나가기 (클라 -> 서버)
EXIT_CHANNEL,
// 맵 이동
CHANGE_MAP,
// 단체로 맵 이동
PARTY_CHANGE_MAP,
// 파티장이 보스 레이드(인스턴스 던전) 입장 신청 (클라 -> 서버)
INTO_BOSS_RAID,
// 플레이어 위치, 방향 (서버 -> 클라 \ 클라 -> 서버)
TRANSFORM_PLAYER,

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,3 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Serilog;
@@ -6,19 +5,22 @@ using Serilog;
namespace ServerLib.Utils;
/// <summary>
/// 릴리즈 빌드 크래시 덤프 핸들러
/// 크래시 핸들러 (Windows / Linux 공통)
/// Register() 를 Program.cs 최상단에서 한 번 호출.
///
/// Register() 를 Program.cs 최상단에서 한 번 호출.
/// 덤프 생성은 CLR 환경변수로 처리 (스택 언와인드 전에 찍힘):
/// DOTNET_DbgEnableMiniDump=1
/// DOTNET_DbgMiniDumpType=4
/// DOTNET_DbgMiniDumpName=crashes/crash_%p_%t.dmp
///
/// 생성 파일 (crashes/ 폴더):
/// Debug : crash_YYYY-MM-DD_HH-mm-ss.log
/// Release : crash_YYYY-MM-DD_HH-mm-ss.log
/// crash_YYYY-MM-DD_HH-mm-ss.dmp ← 메모리 덤프 추가
/// 생성 파일 (crashes/ 폴더):
/// crash_YYYY-MM-DD_HH-mm-ss.log ← 항상 생성
/// crash_%p_%t.dmp ← CLR이 직접 생성 (정확한 크래시 위치)
/// </summary>
public static class CrashDumpHandler
{
private const string CRASH_DIR = "crashes";
private static int registered = 0;
private static int registered;
public static void Register()
{
@@ -39,16 +41,13 @@ public static class CrashDumpHandler
private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception? ex = e.ExceptionObject as Exception;
bool isTerminating = e.IsTerminating;
string tag = $"[CrashDump] UnhandledException (IsTerminating={isTerminating})";
string tag = $"[CrashDump] UnhandledException (IsTerminating={e.IsTerminating})";
WriteCrash(tag, ex);
}
private static void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
{
e.SetObserved(); // 프로세스 종료 방지
string tag = "[CrashDump] UnobservedTaskException";
WriteCrash(tag, e.Exception);
}
@@ -62,25 +61,14 @@ public static class CrashDumpHandler
Directory.CreateDirectory(CRASH_DIR);
string timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
string basePath = Path.Combine(CRASH_DIR, $"crash_{timestamp}");
string logPath = Path.Combine(CRASH_DIR, $"crash_{timestamp}.log");
// 1. 크래시 로그 작성
string logPath = $"{basePath}.log";
WriteCrashLog(logPath, ex);
Log.Fatal("{Tag} → {Log}", tag, logPath);
#if !DEBUG
// 2. 메모리 덤프 작성 (Release only)
string dmpPath = $"{basePath}.dmp";
WriteDumpFile(dmpPath);
Log.Fatal("[CrashDump] 덤프 파일 저장 완료 → {Dmp}", dmpPath);
#endif
}
catch (Exception writeEx)
{
// 덤프 저장 실패는 무시 (이미 크래시 중이므로)
Log.Error(writeEx, "[CrashDump] 덤프 저장 실패");
Log.Error(writeEx, "[CrashDump] 로그 저장 실패");
}
finally
{
@@ -96,21 +84,18 @@ public static class CrashDumpHandler
sb.AppendLine("═══════════════════════════════════════════════════");
sb.AppendLine();
// 환경 정보
sb.AppendLine("[Environment]");
sb.AppendLine($" OS : {RuntimeInformation.OSDescription}");
sb.AppendLine($" Runtime : {RuntimeInformation.FrameworkDescription}");
sb.AppendLine($" PID : {Environment.ProcessId}");
sb.AppendLine($" WorkDir : {Environment.CurrentDirectory}");
sb.AppendLine($" OS : {RuntimeInformation.OSDescription}");
sb.AppendLine($" Runtime : {RuntimeInformation.FrameworkDescription}");
sb.AppendLine($" PID : {Environment.ProcessId}");
sb.AppendLine($" WorkDir : {Environment.CurrentDirectory}");
sb.AppendLine($" MachineName: {Environment.MachineName}");
sb.AppendLine();
// 스레드 정보
sb.AppendLine("[Thread]");
sb.AppendLine($" ThreadId : {Environment.CurrentManagedThreadId}");
sb.AppendLine();
// 예외 정보
sb.AppendLine("[Exception]");
if (ex is null)
{
@@ -118,7 +103,7 @@ public static class CrashDumpHandler
}
else
{
AppendException(sb, ex, depth: 0);
AppendException(sb, ex, 0);
}
File.WriteAllText(path, sb.ToString(), Encoding.UTF8);
@@ -126,7 +111,7 @@ public static class CrashDumpHandler
private static void AppendException(StringBuilder sb, Exception ex, int depth)
{
string indent = new string(' ', depth * 2);
string indent = new(' ', depth * 2);
sb.AppendLine($"{indent} Type : {ex.GetType().FullName}");
sb.AppendLine($"{indent} Message : {ex.Message}");
sb.AppendLine($"{indent} Source : {ex.Source}");
@@ -157,40 +142,4 @@ public static class CrashDumpHandler
AppendException(sb, ex.InnerException, depth + 1);
}
}
#if !DEBUG
// Windows MiniDumpWriteDump P/Invoke
[DllImport("dbghelp.dll", SetLastError = true)]
private static extern bool MiniDumpWriteDump(
IntPtr hProcess, uint processId, IntPtr hFile,
uint dumpType, IntPtr exceptionParam,
IntPtr userStreamParam, IntPtr callbackParam);
private const uint MiniDumpWithFullMemory = 0x00000002;
private static void WriteDumpFile(string path)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Log.Warning("[CrashDump] 덤프 생성은 Windows만 지원");
return;
}
using Process process = Process.GetCurrentProcess();
using FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
bool success = MiniDumpWriteDump(
process.Handle,
(uint)process.Id,
fs.SafeFileHandle.DangerousGetHandle(),
MiniDumpWithFullMemory,
IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
if (!success)
{
int err = Marshal.GetLastWin32Error();
Log.Error("[CrashDump] MiniDumpWriteDump 실패 (Win32 Error={Err})", err);
}
}
#endif
}

View File

@@ -7,4 +7,20 @@
ports:
- "9050:9050/udp" # LiteNetLib UDP 포트
- "9500:9500/udp" # LiteNetLib UDP 포트
- "40001:9500/udp" # LiteNetLib UDP 포트
- "40002:9500/udp" # LiteNetLib UDP 포트
- "40003:9500/udp" # LiteNetLib UDP 포트
- "40004:9500/udp" # LiteNetLib UDP 포트
- "40005:9500/udp" # LiteNetLib UDP 포트
- "40006:9500/udp" # LiteNetLib UDP 포트
- "40007:9500/udp" # LiteNetLib UDP 포트
- "40008:9500/udp" # LiteNetLib UDP 포트
- "40009:9500/udp" # LiteNetLib UDP 포트
- "40100:9500/udp" # LiteNetLib UDP 포트
environment:
- DOTNET_DbgEnableMiniDump=1 # 크래시 시 덤프 자동 생성
- DOTNET_DbgMiniDumpType=4 # 4 = Full dump
- DOTNET_DbgMiniDumpName=/app/crashes/crash_%p_%t.dmp
volumes:
- ./crashes:/app/crashes # 덤프/로그 로컬 마운트
restart: unless-stopped