fix : 서버 버그 수정 작업 머지
Merge branch 'fix/mmo-server-logic-bugs' of https://git.tolelom.xyz/A301/a301_mmo_game_server # Conflicts: # MMOTestServer/MMOserver/Game/GameServer.cs
This commit is contained in:
@@ -18,6 +18,9 @@ public class GameServer : ServerBase
|
||||
private readonly Dictionary<ushort, Action<NetPeer, int, byte[]>> packetHandlers;
|
||||
private readonly UuidGenerator userUuidGenerator;
|
||||
|
||||
// 동일 토큰 동시 인증 방지
|
||||
private readonly HashSet<string> authenticatingTokens = new();
|
||||
|
||||
public GameServer(int port, string connectionString) : base(port, connectionString)
|
||||
{
|
||||
packetHandlers = new Dictionary<ushort, Action<NetPeer, int, byte[]>>
|
||||
@@ -99,54 +102,80 @@ public class GameServer : ServerBase
|
||||
OnSessionConnected(peer, hashKey);
|
||||
}
|
||||
|
||||
protected override async void HandleAuth(NetPeer peer, byte[] payload)
|
||||
protected override async Task HandleAuth(NetPeer peer, byte[] payload)
|
||||
{
|
||||
AccTokenPacket accTokenPacket = Serializer.Deserialize<AccTokenPacket>(new ReadOnlyMemory<byte>(payload));
|
||||
string token = accTokenPacket.Token;
|
||||
string? verifiedUsername = null;
|
||||
tokenHash.TryGetValue(token, out int hashKey);
|
||||
if (hashKey <= 1000)
|
||||
|
||||
// 동일 토큰 동시 인증 방지
|
||||
if (!authenticatingTokens.Add(token))
|
||||
{
|
||||
hashKey = userUuidGenerator.Create();
|
||||
Log.Warning("[Server] 동일 토큰 동시 인증 시도 차단 PeerId={Id}", peer.Id);
|
||||
peer.Disconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
if (sessions.TryGetValue(hashKey, out NetPeer? existing))
|
||||
try
|
||||
{
|
||||
// WiFi → LTE 전환 등 재연결: 이전 피어 교체 (토큰 재검증 불필요)
|
||||
existing.Tag = null;
|
||||
sessions.Remove(hashKey);
|
||||
Log.Information("[Server] 재연결 HashKey={Key} Old={Old} New={New}", hashKey, existing.Id, peer.Id);
|
||||
existing.Disconnect();
|
||||
}
|
||||
else
|
||||
{
|
||||
// 신규 연결: 웹서버에 JWT 검증 요청
|
||||
string? username = await RestApi.Instance.VerifyTokenAsync(token);
|
||||
if (username == null || username.Trim().Length <= 0)
|
||||
string? username = "";
|
||||
int hashKey;
|
||||
bool isReconnect;
|
||||
|
||||
lock (sessionLock)
|
||||
{
|
||||
Log.Warning("[Server] 토큰 검증 실패 - 연결 거부 PeerId={Id}", peer.Id);
|
||||
userUuidGenerator.Release(hashKey);
|
||||
peer.Disconnect();
|
||||
return;
|
||||
isReconnect = tokenHash.TryGetValue(token, out hashKey) && hashKey > 1000;
|
||||
if (!isReconnect)
|
||||
{
|
||||
hashKey = userUuidGenerator.Create();
|
||||
}
|
||||
|
||||
if (isReconnect && sessions.TryGetValue(hashKey, out NetPeer? existing))
|
||||
{
|
||||
// WiFi → LTE 전환 등 재연결: 이전 피어 교체 (토큰 재검증 불필요)
|
||||
existing.Tag = null;
|
||||
sessions.Remove(hashKey);
|
||||
Log.Information("[Server] 재연결 HashKey={Key} Old={Old} New={New}", hashKey, existing.Id, peer.Id);
|
||||
existing.Disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
Log.Information("[Server] 토큰 검증 성공 Username={Username} PeerId={Id}", username, peer.Id);
|
||||
verifiedUsername = username;
|
||||
}
|
||||
if (!isReconnect)
|
||||
{
|
||||
// 신규 연결: 웹서버에 JWT 검증 요청
|
||||
username = await RestApi.Instance.VerifyTokenAsync(token);
|
||||
if (username == null)
|
||||
{
|
||||
Log.Warning("[Server] 토큰 검증 실패 - 연결 거부 PeerId={Id}", peer.Id);
|
||||
userUuidGenerator.Release(hashKey);
|
||||
peer.Disconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
peer.Tag = new Session(hashKey, peer);
|
||||
((Session)peer.Tag).Token = token;
|
||||
if (verifiedUsername != null)
|
||||
Log.Information("[Server] 토큰 검증 성공 Username={Username} PeerId={Id}", username, peer.Id);
|
||||
}
|
||||
|
||||
// await 이후 — 공유 자원 접근 보호
|
||||
lock (sessionLock)
|
||||
{
|
||||
peer.Tag = new Session(hashKey, peer);
|
||||
((Session)peer.Tag).Token = token;
|
||||
if (username.Length > 0)
|
||||
{
|
||||
((Session)peer.Tag).Username = username;
|
||||
}
|
||||
|
||||
sessions[hashKey] = peer;
|
||||
tokenHash[token] = hashKey;
|
||||
pendingPeers.Remove(peer.Id);
|
||||
}
|
||||
|
||||
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
|
||||
OnSessionConnected(peer, hashKey);
|
||||
}
|
||||
finally
|
||||
{
|
||||
((Session)peer.Tag).Username = verifiedUsername;
|
||||
((Session)peer.Tag).UserName = verifiedUsername;
|
||||
authenticatingTokens.Remove(token);
|
||||
}
|
||||
sessions[hashKey] = peer;
|
||||
tokenHash[token] = hashKey;
|
||||
pendingPeers.Remove(peer.Id);
|
||||
|
||||
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
|
||||
OnSessionConnected(peer, hashKey);
|
||||
}
|
||||
|
||||
protected override void OnSessionConnected(NetPeer peer, int hashKey)
|
||||
@@ -336,7 +365,7 @@ public class GameServer : ServerBase
|
||||
{
|
||||
IsAccepted = true,
|
||||
Player = ToPlayerInfo(player),
|
||||
MaplId = channelId
|
||||
MapId = player.CurrentMapId
|
||||
};
|
||||
|
||||
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.LOAD_GAME, packet);
|
||||
@@ -428,10 +457,10 @@ public class GameServer : ServerBase
|
||||
|
||||
// 이전에 다른 채널에 있었는지 체크
|
||||
int preChannelId = cm.HasUser(hashKey);
|
||||
Player? prevPlayer = preChannelId >= 0 ? cm.GetChannel(preChannelId).GetPlayer(hashKey) : null;
|
||||
if (preChannelId >= 0)
|
||||
{
|
||||
// 제거 전에 채널/플레이어 정보 저장 (브로드캐스트에 필요)
|
||||
Player? player = cm.GetChannel(preChannelId).GetPlayer(hashKey);
|
||||
Player? player = prevPlayer;
|
||||
|
||||
// 파티 자동 탈퇴
|
||||
HandlePartyLeaveOnExit(preChannelId, hashKey);
|
||||
@@ -453,6 +482,14 @@ 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);
|
||||
@@ -464,7 +501,7 @@ public class GameServer : ServerBase
|
||||
{
|
||||
HashKey = hashKey,
|
||||
PlayerId = hashKey,
|
||||
Nickname = ((Session)peer.Tag).UserName
|
||||
Nickname = ((Session)peer.Tag).Username ?? ""
|
||||
};
|
||||
|
||||
Session? session = peer.Tag as Session;
|
||||
@@ -548,12 +585,19 @@ public class GameServer : ServerBase
|
||||
ChannelManager cm = ChannelManager.Instance;
|
||||
|
||||
int preChannelId = cm.HasUser(hashKey);
|
||||
|
||||
// 이전에 다른 채널에 있었는지 체크 / 파티이동은 이미 접속한 상태여야 한다.
|
||||
if (preChannelId < 0)
|
||||
{
|
||||
Log.Warning("[GameServer] INTO_CHANNEL_PARTY 채널에 접속하지 않은 유저");
|
||||
return;
|
||||
}
|
||||
|
||||
Channel.Channel preChannel = cm.GetChannel(preChannelId);
|
||||
Channel.Channel newChannel = cm.GetChannel(packet.ChannelId);
|
||||
PartyInfo? preParty = preChannel.GetPartyManager().GetParty(packet.PartyId);
|
||||
|
||||
// 이전에 다른 채널에 있었는지 체크 / 파티이동은 이미 접속한 상태여야 한다.
|
||||
if (preChannelId < 0 || preParty == null)
|
||||
if (preParty == null)
|
||||
{
|
||||
Log.Warning("[GameServer] INTO_CHANNEL_PARTY 해당 파티 없음");
|
||||
return;
|
||||
@@ -574,12 +618,15 @@ public class GameServer : ServerBase
|
||||
return;
|
||||
}
|
||||
|
||||
// 기존 채널에서 제거 + 기존 채널 유저들에게 나감 알림
|
||||
// 기존 채널에서 제거 전에 플레이어 정보 보존
|
||||
Dictionary<int, Player> savedPlayers = new();
|
||||
foreach (int memberId in preParty.PartyMemberIds)
|
||||
{
|
||||
Player? player = preChannel.GetPlayer(memberId);
|
||||
if (player != null)
|
||||
{
|
||||
savedPlayers[memberId] = player;
|
||||
|
||||
UpdateChannelUserPacket exitNotify = new()
|
||||
{
|
||||
Players = ToPlayerInfo(player),
|
||||
@@ -615,12 +662,13 @@ public class GameServer : ServerBase
|
||||
|
||||
if (memberPeer != null)
|
||||
{
|
||||
// 새 채널에 유저 추가
|
||||
// 새 채널에 유저 추가 (보존된 플레이어 정보 사용)
|
||||
string nickname = savedPlayers.TryGetValue(memberId, out Player? saved) ? saved.Nickname : memberId.ToString();
|
||||
Player newPlayer = new()
|
||||
{
|
||||
HashKey = memberId,
|
||||
PlayerId = memberId,
|
||||
Nickname = memberId.ToString()
|
||||
Nickname = nickname
|
||||
};
|
||||
cm.AddUser(packet.ChannelId, memberId, newPlayer, memberPeer);
|
||||
|
||||
@@ -1012,7 +1060,7 @@ public class GameServer : ServerBase
|
||||
}
|
||||
|
||||
SendTo(peer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
|
||||
Log.Debug("[GameServer] CHANGE_MAP HashKey={Key} OldMap={OldMapId} NewMap={MapId}", hashKey, oldMapId, newMapId);
|
||||
Log.Debug("[GameServer] CHANGE_MAP HashKey={Key} OldMap={OldMapId} NewMap={MapId}", hashKey, oldMapId, packet.MapId);
|
||||
}
|
||||
|
||||
private void OnPartyChangeMap(NetPeer peer, int hashKey, byte[] payload)
|
||||
@@ -1092,7 +1140,16 @@ public class GameServer : ServerBase
|
||||
Log.Debug("[GameServer] PARTY_CHANGE_MAP HashKey={Key} PartyId={PartyId} MapId={MapId}", hashKey, packet.PartyId, packet.MapId);
|
||||
}
|
||||
|
||||
private async void OnIntoBossRaid(NetPeer peer, int hashKey, byte[] payload)
|
||||
private void OnIntoBossRaid(NetPeer peer, int hashKey, byte[] payload)
|
||||
{
|
||||
_ = OnIntoBossRaidAsync(peer, hashKey, payload).ContinueWith(t =>
|
||||
{
|
||||
if (t.IsFaulted)
|
||||
Log.Error(t.Exception, "[GameServer] OnIntoBossRaid 예외 HashKey={Key}", hashKey);
|
||||
}, TaskContinuationOptions.OnlyOnFaulted);
|
||||
}
|
||||
|
||||
private async Task OnIntoBossRaidAsync(NetPeer peer, int hashKey, byte[] payload)
|
||||
{
|
||||
IntoBossRaidPacket packet = Serializer.Deserialize<IntoBossRaidPacket>(new ReadOnlyMemory<byte>(payload));
|
||||
|
||||
@@ -1135,85 +1192,105 @@ public class GameServer : ServerBase
|
||||
}
|
||||
}
|
||||
|
||||
BossRaidResult? result = await RestApi.Instance.BossRaidAccesssAsync(userNames, 1);
|
||||
BossRaidResult? result = await RestApi.Instance.BossRaidAccessAsync(userNames, packet.RaidId);
|
||||
|
||||
// 입장 실패
|
||||
if (result == null || result.BossId <= 0)
|
||||
// await 이후 — 공유 자원 접근 보호
|
||||
lock (sessionLock)
|
||||
{
|
||||
SendTo(peer,
|
||||
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
|
||||
new IntoBossRaidPacket { RaidId = -1, IsSuccess = false }));
|
||||
|
||||
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId} Failed", hashKey,
|
||||
party.PartyId, -1);
|
||||
return;
|
||||
}
|
||||
|
||||
// 레이드 맵 할당 (미사용 맵 탐색 → 없으면 동적 생성)
|
||||
int assignedRaidMapId = channel.GetOrCreateAvailableRaidMap();
|
||||
|
||||
// 진행중 맵으로 등록
|
||||
channel.AddInstanceMap(assignedRaidMapId);
|
||||
|
||||
// 파티원 전체 레이드 맵으로 이동 + 각자에게 알림
|
||||
foreach (int memberId in party.PartyMemberIds)
|
||||
{
|
||||
Player? memberPlayer = channel.GetPlayer(memberId);
|
||||
if (memberPlayer == null)
|
||||
// 입장 실패
|
||||
if (result == null || result.BossId <= 0)
|
||||
{
|
||||
continue;
|
||||
SendTo(peer,
|
||||
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
|
||||
new IntoBossRaidPacket { RaidId = -1, IsSuccess = false }));
|
||||
|
||||
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId} Failed", hashKey,
|
||||
party.PartyId, -1);
|
||||
return;
|
||||
}
|
||||
|
||||
// 이전 맵 캐싱 (레이드 종료 후 복귀용)
|
||||
memberPlayer.PreviousMapId = memberPlayer.CurrentMapId;
|
||||
|
||||
int oldMapId = memberPlayer.CurrentMapId;
|
||||
channel.ChangeMap(memberId, memberPlayer, assignedRaidMapId);
|
||||
|
||||
if (!sessions.TryGetValue(memberId, out NetPeer? memberPeer))
|
||||
// await 이후 상태 재검증
|
||||
channelId = cm.HasUser(hashKey);
|
||||
if (channelId < 0)
|
||||
{
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
|
||||
PlayerInfo memberInfo = ToPlayerInfo(memberPlayer);
|
||||
|
||||
// 기존 맵 유저들에게 퇴장 알림
|
||||
ChangeMapPacket exitNotify = new() { MapId = oldMapId, IsAdd = false, Player = memberInfo };
|
||||
BroadcastToMap(channelId, oldMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, exitNotify));
|
||||
|
||||
// 새 맵 유저들에게 입장 알림 (본인 제외)
|
||||
ChangeMapPacket enterNotify = new() { MapId = assignedRaidMapId, IsAdd = true, Player = memberInfo };
|
||||
BroadcastToMap(channelId, assignedRaidMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, enterNotify),
|
||||
memberPeer);
|
||||
|
||||
// 본인에게 새 맵 플레이어 목록 전달
|
||||
ChangeMapPacket response = new() { MapId = assignedRaidMapId };
|
||||
AMap? raidMap = channel.GetMap(assignedRaidMapId);
|
||||
if (raidMap != null)
|
||||
channel = cm.GetChannel(channelId);
|
||||
party = channel.GetPartyManager().GetPartyByPlayer(hashKey);
|
||||
if (party == null)
|
||||
{
|
||||
foreach ((int uid, Player p) in raidMap.GetUsers())
|
||||
return;
|
||||
}
|
||||
|
||||
// 레이드 맵 할당 (미사용 맵 탐색 → 없으면 동적 생성)
|
||||
int assignedRaidMapId = channel.GetOrCreateAvailableRaidMap();
|
||||
|
||||
// 진행중 맵으로 등록
|
||||
channel.AddInstanceMap(assignedRaidMapId);
|
||||
|
||||
// 파티원 전체 레이드 맵으로 이동 + 각자에게 알림
|
||||
foreach (int memberId in party.PartyMemberIds)
|
||||
{
|
||||
Player? memberPlayer = channel.GetPlayer(memberId);
|
||||
if (memberPlayer == null)
|
||||
{
|
||||
if (uid != memberId)
|
||||
continue;
|
||||
}
|
||||
|
||||
// 이전 맵 캐싱 (레이드 종료 후 복귀용)
|
||||
memberPlayer.PreviousMapId = memberPlayer.CurrentMapId;
|
||||
|
||||
int oldMapId = memberPlayer.CurrentMapId;
|
||||
channel.ChangeMap(memberId, memberPlayer, assignedRaidMapId);
|
||||
|
||||
if (!sessions.TryGetValue(memberId, out NetPeer? memberPeer))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
PlayerInfo memberInfo = ToPlayerInfo(memberPlayer);
|
||||
|
||||
// 기존 맵 유저들에게 퇴장 알림
|
||||
ChangeMapPacket exitNotify = new() { MapId = oldMapId, IsAdd = false, Player = memberInfo };
|
||||
BroadcastToMap(channelId, oldMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, exitNotify));
|
||||
|
||||
// 새 맵 유저들에게 입장 알림 (본인 제외)
|
||||
ChangeMapPacket enterNotify = new() { MapId = assignedRaidMapId, IsAdd = true, Player = memberInfo };
|
||||
BroadcastToMap(channelId, assignedRaidMapId, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, enterNotify),
|
||||
memberPeer);
|
||||
|
||||
// 본인에게 새 맵 플레이어 목록 전달
|
||||
ChangeMapPacket response = new() { MapId = assignedRaidMapId };
|
||||
AMap? raidMap = channel.GetMap(assignedRaidMapId);
|
||||
if (raidMap != null)
|
||||
{
|
||||
foreach ((int uid, Player p) in raidMap.GetUsers())
|
||||
{
|
||||
response.Players.Add(ToPlayerInfo(p));
|
||||
if (uid != memberId)
|
||||
{
|
||||
response.Players.Add(ToPlayerInfo(p));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SendTo(memberPeer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
|
||||
|
||||
// 각 파티원에게 레이드 입장 결과 전달 (Session, Token 포함)
|
||||
SendTo(memberPeer,
|
||||
PacketSerializer.Serialize((ushort)PacketCode.INTO_BOSS_RAID,
|
||||
new IntoBossRaidPacket
|
||||
{
|
||||
RaidId = assignedRaidMapId, IsSuccess = true, Session = result.SessionName,
|
||||
Token = result.Tokens != null && result.Tokens.TryGetValue(memberPlayer.Nickname, out string? memberToken)
|
||||
? memberToken
|
||||
: ""
|
||||
}));
|
||||
}
|
||||
|
||||
SendTo(memberPeer, PacketSerializer.Serialize((ushort)PacketCode.CHANGE_MAP, response));
|
||||
|
||||
// 각 멤버에게 개별 토큰과 함께 레이드 이동 알림
|
||||
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);
|
||||
}
|
||||
|
||||
Log.Debug("[GameServer] INTO_BOSS_RAID HashKey={Key} PartyId={PartyId} AssignedRaidMapId={RaidId}", hashKey, party.PartyId,
|
||||
assignedRaidMapId);
|
||||
}
|
||||
|
||||
// 채널 퇴장/연결 해제 시 파티 자동 탈퇴 처리
|
||||
@@ -1229,8 +1306,8 @@ public class GameServer : ServerBase
|
||||
|
||||
pm.LeaveParty(hashKey, out PartyInfo? remaining);
|
||||
|
||||
// 0명 → DELETE, 남은 멤버 있음 → LEAVE
|
||||
UpdatePartyPacket notify = remaining != null
|
||||
// 남은 멤버 있음 → LEAVE, 0명(파티 해산됨) → DELETE
|
||||
UpdatePartyPacket notify = remaining != null && remaining.PartyMemberIds.Count > 0
|
||||
? new UpdatePartyPacket
|
||||
{
|
||||
PartyId = partyId.Value,
|
||||
|
||||
Reference in New Issue
Block a user