1 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
9 changed files with 255 additions and 355 deletions

View File

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

View File

@@ -35,7 +35,7 @@ public class RestApi : Singleton<RestApi>
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Log.Warning("[RestApi] 토큰 인증 실패 (401)");
return null;
return "";
}
response.EnsureSuccessStatusCode();
@@ -56,7 +56,7 @@ public class RestApi : Singleton<RestApi>
}
}
return null;
return "";
}
private sealed class AuthVerifyResponse
@@ -71,7 +71,7 @@ public class RestApi : Singleton<RestApi>
// 레이드 채널 접속 여부 체크
// 성공 시 BossRaidResult 반환, 실패/거절 시 null 반환
public async Task<BossRaidResult?> BossRaidAccessAsync(List<string> userNames, int bossId)
public async Task<BossRaidResult?> BossRaidAccesssAsync(List<string> userNames, int bossId)
{
string url = AppConfig.RestApi.BaseUrl + "/api/internal/bossraid/entry";
@@ -88,12 +88,17 @@ public class RestApi : Singleton<RestApi>
return null;
}
// 400: 입장 조건 미충족 / 409: 이미 레이드 중
if (response.StatusCode == HttpStatusCode.BadRequest ||
response.StatusCode == HttpStatusCode.Conflict)
// 400: 입장 조건 미충족 (레벨 부족)
if (response.StatusCode == HttpStatusCode.BadRequest)
{
Log.Warning("[RestApi] 보스 레이드 입장 거절 ({Status}) BossId={BossId}",
(int)response.StatusCode, bossId);
Log.Warning("[RestApi] 보스 레이드 입장 거절 (400) BossId={BossId}", bossId);
return null;
}
// 409: 이미 진행 중이거나 슬롯 충돌
if (response.StatusCode == HttpStatusCode.Conflict)
{
Log.Warning("[RestApi] 보스 레이드 충돌 (409) BossId={BossId} - 이미 진행 중이거나 슬롯 없음", bossId);
return null;
}
@@ -113,7 +118,7 @@ public class RestApi : Singleton<RestApi>
BossId = raw.BossId,
Players = raw.Players,
Status = raw.Status ?? string.Empty,
Tokens = raw.Tokens
Tokens = raw.Tokens ?? new()
};
}
catch (Exception ex) when (attempt < MAX_RETRY)

View File

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

View File

@@ -18,9 +18,6 @@ public class GameServer : ServerBase
private readonly Dictionary<ushort, Action<NetPeer, int, byte[]>> packetHandlers;
private readonly UuidGenerator userUuidGenerator;
// 동일 토큰 동시 인증 방지
private readonly HashSet<string> authenticatingTokens = new();
public GameServer(int port, string connectionString) : base(port, connectionString)
{
packetHandlers = new Dictionary<ushort, Action<NetPeer, int, byte[]>>
@@ -102,80 +99,53 @@ public class GameServer : ServerBase
OnSessionConnected(peer, hashKey);
}
protected override async Task HandleAuth(NetPeer peer, byte[] payload)
protected override async void HandleAuth(NetPeer peer, byte[] payload)
{
AccTokenPacket accTokenPacket = Serializer.Deserialize<AccTokenPacket>(new ReadOnlyMemory<byte>(payload));
string token = accTokenPacket.Token;
// 동일 토큰 동시 인증 방지
if (!authenticatingTokens.Add(token))
string username = "";
tokenHash.TryGetValue(token, out int hashKey);
if (hashKey <= 1000)
{
Log.Warning("[Server] 동일 토큰 동시 인증 시도 차단 PeerId={Id}", peer.Id);
peer.Disconnect();
return;
hashKey = userUuidGenerator.Create();
}
try
if (sessions.TryGetValue(hashKey, out NetPeer? existing))
{
string username = "";
int hashKey;
bool isReconnect;
lock (sessionLock)
{
isReconnect = tokenHash.TryGetValue(token, out hashKey) && hashKey > 1000;
if (!isReconnect)
{
hashKey = userUuidGenerator.Create();
}
if (isReconnect && sessions.TryGetValue(hashKey, out NetPeer? existing))
{
// WiFi → LTE 전환 등 재연결: 이전 피어 교체 (토큰 재검증 불필요)
existing.Tag = null;
sessions.Remove(hashKey);
Log.Information("[Server] 재연결 HashKey={Key} Old={Old} New={New}", hashKey, existing.Id, peer.Id);
existing.Disconnect();
}
}
if (!isReconnect)
{
// 신규 연결: 웹서버에 JWT 검증 요청
username = await RestApi.Instance.VerifyTokenAsync(token);
if (username == null)
{
Log.Warning("[Server] 토큰 검증 실패 - 연결 거부 PeerId={Id}", peer.Id);
userUuidGenerator.Release(hashKey);
peer.Disconnect();
return;
}
Log.Information("[Server] 토큰 검증 성공 Username={Username} PeerId={Id}", username, peer.Id);
}
// await 이후 — 공유 자원 접근 보호
lock (sessionLock)
{
peer.Tag = new Session(hashKey, peer);
((Session)peer.Tag).Token = token;
if (username.Length > 0)
{
((Session)peer.Tag).UserName = username;
}
sessions[hashKey] = peer;
tokenHash[token] = hashKey;
pendingPeers.Remove(peer.Id);
}
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
OnSessionConnected(peer, hashKey);
// WiFi → LTE 전환 등 재연결: 이전 피어 교체 (토큰 재검증 불필요)
existing.Tag = null;
sessions.Remove(hashKey);
Log.Information("[Server] 재연결 HashKey={Key} Old={Old} New={New}", hashKey, existing.Id, peer.Id);
existing.Disconnect();
}
finally
else
{
authenticatingTokens.Remove(token);
// 신규 연결: 웹서버에 JWT 검증 요청
username = await RestApi.Instance.VerifyTokenAsync(token);
if (username == null)
{
Log.Warning("[Server] 토큰 검증 실패 - 연결 거부 PeerId={Id}", peer.Id);
userUuidGenerator.Release(hashKey);
peer.Disconnect();
return;
}
Log.Information("[Server] 토큰 검증 성공 Username={Username} PeerId={Id}", username, peer.Id);
}
peer.Tag = new Session(hashKey, peer);
((Session)peer.Tag).Token = token;
if (username.Length > 0)
{
((Session)peer.Tag).UserName = username;
}
sessions[hashKey] = peer;
tokenHash[token] = hashKey;
pendingPeers.Remove(peer.Id);
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
OnSessionConnected(peer, hashKey);
}
protected override void OnSessionConnected(NetPeer peer, int hashKey)
@@ -216,9 +186,6 @@ public class GameServer : ServerBase
// 파티 자동 탈퇴
HandlePartyLeaveOnExit(channelId, hashKey);
// 레이드 맵이었으면 해제 체크
TryReleaseRaidMap(cm.GetChannel(channelId), player.CurrentMapId);
// 같은 채널 유저들에게 나갔다고 알림
SendExitChannelPacket(peer, hashKey, channelId, player);
}
@@ -368,7 +335,7 @@ public class GameServer : ServerBase
{
IsAccepted = true,
Player = ToPlayerInfo(player),
MapId = player.CurrentMapId
MaplId = channelId
};
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.LOAD_GAME, packet);
@@ -439,7 +406,12 @@ public class GameServer : ServerBase
Mp = player.Mp,
MaxMp = player.MaxMp,
Position = new Position { X = player.PosX, Y = player.PosY, Z = player.PosZ },
RotY = player.RotY
RotY = player.RotY,
Experience = player.Experience,
NextExp = player.NextExp,
AttackPower = player.AttackPower,
AttackRange = player.AttackRange,
SprintMultiplier = player.SprintMultiplier
};
}
@@ -455,20 +427,14 @@ public class GameServer : ServerBase
// 이전에 다른 채널에 있었는지 체크
int preChannelId = cm.HasUser(hashKey);
Player? prevPlayer = preChannelId >= 0 ? cm.GetChannel(preChannelId).GetPlayer(hashKey) : null;
if (preChannelId >= 0)
{
Player? player = prevPlayer;
// 제거 전에 채널/플레이어 정보 저장 (브로드캐스트에 필요)
Player? player = cm.GetChannel(preChannelId).GetPlayer(hashKey);
// 파티 자동 탈퇴
HandlePartyLeaveOnExit(preChannelId, hashKey);
// 레이드 맵 해제 체크
if (player != null)
{
TryReleaseRaidMap(cm.GetChannel(preChannelId), player.CurrentMapId);
}
cm.RemoveUser(hashKey);
Log.Debug("[GameServer] EXIT_CHANNEL HashKey={Key} PlayerId={PlayerId}", hashKey, preChannelId);
@@ -486,14 +452,6 @@ public class GameServer : ServerBase
{
Log.Warning("[GameServer] INTO_CHANNEL 채널 인원 초과 HashKey={Key} ChannelId={ChannelId} UserCount={Count}/{Max}",
hashKey, packet.ChannelId, newChannel.UserCount, newChannel.UserCountMax);
// 이전 채널에서 이미 제거된 경우 → 이전 채널로 복귀
if (preChannelId >= 0 && prevPlayer != null)
{
cm.AddUser(preChannelId, hashKey, prevPlayer, peer);
Log.Information("[GameServer] INTO_CHANNEL 만석 → 이전 채널({ChannelId})로 복귀 HashKey={Key}", preChannelId, hashKey);
}
byte[] full = PacketSerializer.Serialize((ushort)PacketCode.INTO_CHANNEL,
new IntoChannelPacket { ChannelId = -1 });
SendTo(peer, full);
@@ -554,19 +512,12 @@ public class GameServer : ServerBase
ChannelManager cm = ChannelManager.Instance;
int preChannelId = cm.HasUser(hashKey);
// 이전에 다른 채널에 있었는지 체크 / 파티이동은 이미 접속한 상태여야 한다.
if (preChannelId < 0)
{
Log.Warning("[GameServer] INTO_CHANNEL_PARTY 채널에 접속하지 않은 유저");
return;
}
Channel.Channel preChannel = cm.GetChannel(preChannelId);
Channel.Channel newChannel = cm.GetChannel(packet.ChannelId);
PartyInfo? preParty = preChannel.GetPartyManager().GetParty(packet.PartyId);
if (preParty == null)
// 이전에 다른 채널에 있었는지 체크 / 파티이동은 이미 접속한 상태여야 한다.
if (preChannelId < 0 || preParty == null)
{
Log.Warning("[GameServer] INTO_CHANNEL_PARTY 해당 파티 없음");
return;
@@ -587,15 +538,12 @@ public class GameServer : ServerBase
return;
}
// 기존 채널에서 제거 전에 플레이어 정보 보존
Dictionary<int, Player> savedPlayers = new();
// 기존 채널에서 제거 + 기존 채널 유저들에게 나감 알림
foreach (int memberId in preParty.PartyMemberIds)
{
Player? player = preChannel.GetPlayer(memberId);
if (player != null)
{
savedPlayers[memberId] = player;
UpdateChannelUserPacket exitNotify = new()
{
Players = ToPlayerInfo(player),
@@ -631,8 +579,12 @@ public class GameServer : ServerBase
if (memberPeer != null)
{
// 새 채널에 유저 추가 (보존된 플레이어 정보 사용)
string nickname = savedPlayers.TryGetValue(memberId, out Player? saved) ? saved.Nickname : memberId.ToString();
// 세션에서 username 조회
string nickname = memberPeer.Tag is Session s && !string.IsNullOrEmpty(s.UserName)
? s.UserName
: memberId.ToString();
// 새 채널에 유저 추가
Player newPlayer = new()
{
HashKey = memberId,
@@ -685,12 +637,6 @@ public class GameServer : ServerBase
if (channelId >= 0)
{
HandlePartyLeaveOnExit(channelId, hashKey);
// 레이드 맵 해제 체크
if (player != null)
{
TryReleaseRaidMap(cm.GetChannel(channelId), player.CurrentMapId);
}
}
cm.RemoveUser(hashKey);
@@ -726,9 +672,6 @@ public class GameServer : ServerBase
player.PosZ = packet.Position.Z;
player.RotY = packet.RotY;
// PlayerId 강제 교체 (클라이언트 스푸핑 방지)
packet.PlayerId = hashKey;
// 같은 맵 유저들에게 위치/방향 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.TRANSFORM_PLAYER, packet);
BroadcastToMap(channelId, player.CurrentMapId, data, peer, DeliveryMethod.Unreliable);
@@ -751,9 +694,6 @@ public class GameServer : ServerBase
return;
}
// PlayerId 강제 교체 (클라이언트 스푸핑 방지)
packet.PlayerId = hashKey;
// 같은 맵 유저들에게 행동 브로드캐스트 (나 제외)
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.ACTION_PLAYER, packet);
BroadcastToMap(channelId, player.CurrentMapId, data, peer);
@@ -777,15 +717,6 @@ public class GameServer : ServerBase
return;
}
// PlayerId 강제 교체 (클라이언트 스푸핑 방지)
packet.PlayerId = hashKey;
// HP/MP 범위 클램핑 (클라이언트 조작 방지)
if (packet.MaxHp < 0) packet.MaxHp = 0;
if (packet.MaxMp < 0) packet.MaxMp = 0;
packet.Hp = Math.Clamp(packet.Hp, 0, packet.MaxHp);
packet.Mp = Math.Clamp(packet.Mp, 0, packet.MaxMp);
player.Hp = packet.Hp;
player.MaxHp = packet.MaxHp;
player.Mp = packet.Mp;
@@ -1036,10 +967,6 @@ public class GameServer : ServerBase
}
SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
// 레이드 맵(1001+)에서 나갔고 남은 유저가 0이면 인스턴스 맵 해제
TryReleaseRaidMap(channel, oldMapId);
Log.Debug("[GameServer] CHANGE_MAP HashKey={Key} OldMap={OldMapId} NewMap={MapId}", hashKey, oldMapId, packet.MapId);
}
@@ -1120,16 +1047,7 @@ public class GameServer : ServerBase
Log.Debug("[GameServer] PARTY_CHANGE_MAP HashKey={Key} PartyId={PartyId} MapId={MapId}", hashKey, packet.PartyId, packet.MapId);
}
private void OnIntoBossRaid(NetPeer peer, int hashKey, byte[] payload)
{
_ = OnIntoBossRaidAsync(peer, hashKey, payload).ContinueWith(t =>
{
if (t.IsFaulted)
Log.Error(t.Exception, "[GameServer] OnIntoBossRaid 예외 HashKey={Key}", hashKey);
}, TaskContinuationOptions.OnlyOnFaulted);
}
private async Task OnIntoBossRaidAsync(NetPeer peer, int hashKey, byte[] payload)
private async void OnIntoBossRaid(NetPeer peer, int hashKey, byte[] payload)
{
IntoBossRaidPacket packet = Serializer.Deserialize<IntoBossRaidPacket>(new ReadOnlyMemory<byte>(payload));
@@ -1164,6 +1082,38 @@ public class GameServer : ServerBase
// 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)
@@ -1171,103 +1121,55 @@ public class GameServer : ServerBase
continue;
}
userNames.Add(memberPlayer.Nickname);
}
// 이전 맵 캐싱 (레이드 종료 후 복귀용)
memberPlayer.PreviousMapId = memberPlayer.CurrentMapId;
BossRaidResult? result = await RestApi.Instance.BossRaidAccessAsync(userNames, packet.RaidId);
int oldMapId = memberPlayer.CurrentMapId;
channel.ChangeMap(memberId, memberPlayer, assignedRaidMapId);
// await 이후 — 공유 자원 접근 보호
lock (sessionLock)
{
// 입장 실패
if (result == null || result.BossId <= 0)
if (!sessions.TryGetValue(memberId, out NetPeer? memberPeer))
{
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;
continue;
}
// await 이후 상태 재검증
channelId = cm.HasUser(hashKey);
if (channelId < 0)
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)
{
return;
}
channel = cm.GetChannel(channelId);
party = channel.GetPartyManager().GetPartyByPlayer(hashKey);
if (party == null)
{
return;
}
// 레이드 맵 할당 (미사용 맵 탐색 → 없으면 동적 생성)
int assignedRaidMapId = channel.GetOrCreateAvailableRaidMap();
// 진행중 맵으로 등록
channel.AddInstanceMap(assignedRaidMapId);
// 파티원 전체 레이드 맵으로 이동 + 각자에게 알림
foreach (int memberId in party.PartyMemberIds)
{
Player? memberPlayer = channel.GetPlayer(memberId);
if (memberPlayer == null)
foreach ((int uid, Player p) in raidMap.GetUsers())
{
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)
{
if (uid != memberId)
{
response.Players.Add(ToPlayerInfo(p));
}
response.Players.Add(ToPlayerInfo(p));
}
}
SendTo(memberPeer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
// 각 파티원에게 레이드 입장 결과 전달 (Session, Token 포함)
SendTo(memberPeer,
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
new IntoBossRaidPacket
{ RaidId = assignedRaidMapId, IsSuccess = true, Session = result.SessionName, Token = result.Tokens != null && result.Tokens.TryGetValue(memberPlayer.Nickname, out string? memberToken) ? memberToken : null }));
}
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId}", hashKey, party.PartyId,
assignedRaidMapId);
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);
}
// 채널 퇴장/연결 해제 시 파티 자동 탈퇴 처리
@@ -1283,8 +1185,8 @@ public class GameServer : ServerBase
pm.LeaveParty(hashKey, out PartyInfo? remaining);
// 남은 멤버 있음 → LEAVE, 0명(파티 해산됨) → DELETE
UpdatePartyPacket notify = remaining != null && remaining.PartyMemberIds.Count > 0
// 0명 → DELETE, 남은 멤버 있음 → LEAVE
UpdatePartyPacket notify = remaining != null
? new UpdatePartyPacket
{
PartyId = partyId.Value,
@@ -1304,22 +1206,6 @@ public class GameServer : ServerBase
BroadcastToChannel(channelId, data);
}
// 레이드 맵(1001+)에서 유저가 빠졌을 때, 남은 유저가 0이면 인스턴스 맵 해제
private static void TryReleaseRaidMap(Channel.Channel channel, int mapId)
{
if (mapId < 1001)
{
return;
}
AMap? map = channel.GetMap(mapId);
if (map != null && map.GetUsers().Count == 0)
{
channel.RemoveInstanceMap(mapId);
Log.Debug("[GameServer] 레이드 맵 해제 MapId={MapId}", mapId);
}
}
private void SendError(NetPeer peer, ErrorCode code)
{
ErrorPacket err = new() { Code = code };

View File

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

View File

@@ -75,6 +75,38 @@ public class Player
set;
}
// 경험치
public int Experience
{
get;
set;
}
public int NextExp
{
get;
set;
}
// 전투 스탯
public float AttackPower
{
get;
set;
}
public float AttackRange
{
get;
set;
}
public float SprintMultiplier
{
get;
set;
}
// 현재 위치한 맵 ID
public int CurrentMapId
{

View File

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

View File

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

View File

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