6 Commits

20 changed files with 506 additions and 133 deletions

View File

@@ -11,10 +11,18 @@ public class DummyClientService
// 모든거 강종 // 모든거 강종
public event Action? OnAllDisconnected; public event Action? OnAllDisconnected;
public DummyClientService(int count, string ip, int port, string key, int sendIntervalMs = 1000) public DummyClientService(int count, string ip, int port, string key, int sendIntervalMs = 1000, MapBounds? mapBounds = null)
{ {
sendInterval = sendIntervalMs; sendInterval = sendIntervalMs;
clients = Enumerable.Range(1, count + 1).Select(i => new DummyClients(i, ip, port, key)).ToList(); clients = Enumerable.Range(1, count).Select(i =>
{
DummyClients client = new DummyClients(i, ip, port, key);
if (mapBounds != null)
{
client.Map = mapBounds;
}
return client;
}).ToList();
Log.Information("[SERVICE] {Count}개 클라이언트 생성 → {Ip}:{Port}", count, ip, port); Log.Information("[SERVICE] {Count}개 클라이언트 생성 → {Ip}:{Port}", count, ip, port);
} }
@@ -30,30 +38,23 @@ public class DummyClientService
{ {
foreach (DummyClients c in clients) foreach (DummyClients c in clients)
{ {
c.PollEvents(); try
{
c.PollEvents();
}
catch (Exception ex)
{
Log.Error("[Client {ClientId}] PollEvents 예외: {Ex}", c.clientId, ex.Message);
}
} }
try await Task.Delay(10);
{
await Task.Delay(10, ct);
}
catch (OperationCanceledException)
{
break;
}
} }
} }
private async Task SendLoopAsync(CancellationToken ct) private async Task SendLoopAsync(CancellationToken ct)
{ {
try await Task.Delay(500);
{
await Task.Delay(500, ct);
}
catch (OperationCanceledException)
{
return;
}
int tick = 0; int tick = 0;
@@ -85,14 +86,7 @@ public class DummyClientService
Log.Debug("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total); Log.Debug("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total);
tick++; tick++;
try await Task.Delay(sendInterval);
{
await Task.Delay(sendInterval, ct);
}
catch (OperationCanceledException)
{
break;
}
} }
} }

View File

@@ -28,6 +28,9 @@ public class DummyClients
private float dirX = 0f; private float dirX = 0f;
private float dirZ = 0f; private float dirZ = 0f;
// 맵 경계
public MapBounds Map { get; set; } = new MapBounds(-50f, 50f, -50f, 50f);
// 통계 // 통계
public int SentCount public int SentCount
{ {
@@ -60,10 +63,10 @@ public class DummyClients
Log.Information("[Client {ClientId:00}] 연결됨", this.clientId); Log.Information("[Client {ClientId:00}] 연결됨", this.clientId);
// clientID가 토큰의 hashKey라고 가정함 // clientID가 토큰의 hashKey라고 가정함
AccTokenPacket recvTokenPacket = new AccTokenPacket(); DummyAccTokenPacket recvTokenPacket = new DummyAccTokenPacket();
recvTokenPacket.Token = clientId; recvTokenPacket.Token = clientId;
byte[] data = PacketSerializer.Serialize((ushort)PacketCode.ACC_TOKEN, recvTokenPacket); byte[] data = PacketSerializer.Serialize((ushort)PacketCode.DUMMY_ACC_TOKEN, recvTokenPacket);
writer.Put(data); writer.Put(data);
peer.Send(writer, DeliveryMethod.ReliableOrdered); peer.Send(writer, DeliveryMethod.ReliableOrdered);
writer.Reset(); writer.Reset();
@@ -71,15 +74,6 @@ public class DummyClients
listener.NetworkReceiveEvent += (peer, reader, channel, deliveryMethod) => listener.NetworkReceiveEvent += (peer, reader, channel, deliveryMethod) =>
{ {
short code = reader.GetShort();
short bodyLength = reader.GetShort();
string? msg = reader.GetString();
if (msg != null)
{
RttCount++;
}
ReceivedCount++; ReceivedCount++;
reader.Recycle(); reader.Recycle();
}; };
@@ -104,8 +98,12 @@ public class DummyClients
// 남은 거리가 없으면 새 방향·목표 거리 설정 // 남은 거리가 없으면 새 방향·목표 거리 설정
if (distance <= 0f) if (distance <= 0f)
{ {
// 현재 각도에서 -30~+30도 범위로 회전 // 벽에 붙어있으면 반대 방향 강제, 아니면 ±30도 회전
rotY = (rotY + Random.Shared.Next(-30, 31) + 360) % 360; int wallRotY = Map.GetRotYAwayFromWall(posX, posZ);
rotY = wallRotY >= 0
? (wallRotY + Random.Shared.Next(-30, 31) + 360) % 360
: (rotY + Random.Shared.Next(-30, 31) + 360) % 360;
float rad = rotY * MathF.PI / 180f; float rad = rotY * MathF.PI / 180f;
dirX = MathF.Sin(rad); dirX = MathF.Sin(rad);
dirZ = MathF.Cos(rad); dirZ = MathF.Cos(rad);
@@ -117,9 +115,14 @@ public class DummyClients
// 이번 틱 이동량 (남은 거리 초과 방지) // 이번 틱 이동량 (남은 거리 초과 방지)
float step = MathF.Min(moveSpeed * delta, distance); float step = MathF.Min(moveSpeed * delta, distance);
posX += dirX * step; float nextX = posX + dirX * step;
posZ += dirZ * step; float nextZ = posZ + dirZ * step;
distance -= step;
// 벽 충돌 시 clamp + 다음 틱에 방향 재설정
bool hitWall = Map.Clamp(ref nextX, ref nextZ);
posX = nextX;
posZ = nextZ;
distance = hitWall ? 0f : distance - step;
// 정수 Vector3 갱신 // 정수 Vector3 갱신
position.X = (int)MathF.Round(posX); position.X = (int)MathF.Round(posX);

View File

@@ -0,0 +1,116 @@
namespace ClientTester.DummyService;
public class MapBounds
{
public float MinX
{
get;
set;
}
public float MaxX
{
get;
set;
}
public float MinZ
{
get;
set;
}
public float MaxZ
{
get;
set;
}
public MapBounds(float minX, float maxX, float minZ, float maxZ)
{
MinX = minX;
MaxX = maxX;
MinZ = minZ;
MaxZ = maxZ;
}
// 위치가 경계 안에 있는지 체크
public bool IsInside(float x, float z)
{
return x >= MinX && x <= MaxX && z >= MinZ && z <= MaxZ;
}
// 경계 초과 시 clamp, 벽에 부딪혔으면 true 반환
public bool Clamp(ref float x, ref float z)
{
bool hit = false;
if (x < MinX)
{
x = MinX;
hit = true;
}
else if (x > MaxX)
{
x = MaxX;
hit = true;
}
if (z < MinZ)
{
z = MinZ;
hit = true;
}
else if (z > MaxZ)
{
z = MaxZ;
hit = true;
}
return hit;
}
// 현재 위치 기준으로 벽 반대 방향 rotY 계산 (벽 없으면 -1)
public int GetRotYAwayFromWall(float x, float z, float margin = 0.5f)
{
bool atLeft = x <= MinX + margin;
bool atRight = x >= MaxX - margin;
bool atBottom = z <= MinZ + margin;
bool atTop = z >= MaxZ - margin;
if (!atLeft && !atRight && !atBottom && !atTop)
{
return -1; // 벽 근처 아님
}
// 벽 반대 방향 벡터 합산
float awayX = 0f, awayZ = 0f;
if (atLeft)
{
awayX += 1f;
}
if (atRight)
{
awayX -= 1f;
}
if (atBottom)
{
awayZ += 1f;
}
if (atTop)
{
awayZ -= 1f;
}
// 정규화
float len = MathF.Sqrt(awayX * awayX + awayZ * awayZ);
awayX /= len;
awayZ /= len;
// 방향 벡터 → rotY (degree)
return ((int)(MathF.Atan2(awayX, awayZ) * 180f / MathF.PI) + 360) % 360;
}
}

View File

@@ -59,27 +59,13 @@ public class EchoDummyClientService
c.PollEvents(); c.PollEvents();
} }
try await Task.Delay(10);
{
await Task.Delay(10, ct);
}
catch (OperationCanceledException)
{
break;
}
} }
} }
private async Task SendLoopAsync(CancellationToken ct) private async Task SendLoopAsync(CancellationToken ct)
{ {
try await Task.Delay(500);
{
await Task.Delay(500, ct);
}
catch (OperationCanceledException)
{
return;
}
int tick = 0; int tick = 0;
@@ -111,14 +97,7 @@ public class EchoDummyClientService
Log.Debug("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total); Log.Debug("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total);
tick++; tick++;
try await Task.Delay(sendInterval);
{
await Task.Delay(sendInterval, ct);
}
catch (OperationCanceledException)
{
break;
}
} }
} }

View File

@@ -1,8 +1,10 @@
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Diagnostics; using System.Diagnostics;
using System.Text;
using ClientTester.Packet; using ClientTester.Packet;
using LiteNetLib; using LiteNetLib;
using LiteNetLib.Utils; using LiteNetLib.Utils;
using ProtoBuf;
using Serilog; using Serilog;
namespace ClientTester.EchoDummyService; namespace ClientTester.EchoDummyService;
@@ -75,10 +77,14 @@ public class EchoDummyClients
{ {
short code = reader.GetShort(); short code = reader.GetShort();
short bodyLength = reader.GetShort(); short bodyLength = reader.GetShort();
string? msg = reader.GetString();
byte[] payloadBytes = new byte[bodyLength];
reader.GetBytes(payloadBytes, bodyLength);
EchoPacket echoPacket = PacketSerializer.DeserializePayload<EchoPacket>(payloadBytes);
string msg = echoPacket.Str;
long sentTick; long sentTick;
if (msg != null && msg.StartsWith("Echo seq:") && if (msg.StartsWith("Echo seq:") &&
int.TryParse(msg.Substring("Echo seq:".Length), out int seq) && int.TryParse(msg.Substring("Echo seq:".Length), out int seq) &&
pendingPings.TryRemove(seq, out sentTick)) pendingPings.TryRemove(seq, out sentTick))
{ {
@@ -131,12 +137,12 @@ public class EchoDummyClients
} }
} }
PacketHeader packetHeader = new PacketHeader(); // string → raw bytes (길이 prefix 방지)
packetHeader.Code = 0; EchoPacket echoPacket = new EchoPacket();
packetHeader.BodyLength = (ushort)$"Echo seq:{seq}".Length; echoPacket.Str = $"Echo seq:{seq}";
writer.Put((short)packetHeader.Code);
writer.Put((short)packetHeader.BodyLength); byte[] data = PacketSerializer.Serialize<EchoPacket>((ushort)PacketCode.ECHO, echoPacket);
writer.Put($"Echo seq:{seq}"); writer.Put(data);
// 순서보장 안함 HOL Blocking 제거 // 순서보장 안함 HOL Blocking 제거
peer.Send(writer, DeliveryMethod.ReliableUnordered); peer.Send(writer, DeliveryMethod.ReliableUnordered);
SentCount++; SentCount++;

View File

@@ -4,6 +4,22 @@ using ProtoBuf;
namespace ClientTester.Packet; namespace ClientTester.Packet;
// ============================================================
// 에코용
// ============================================================
// ECHO
[ProtoContract]
public class EchoPacket
{
[ProtoMember(1)]
public string Str
{
get;
set;
}
}
// ============================================================ // ============================================================
// 공통 타입 // 공통 타입
// ============================================================ // ============================================================
@@ -104,12 +120,24 @@ public class PlayerInfo
// 인증 // 인증
// ============================================================ // ============================================================
// DUMMY_ACC_TOKEN
[ProtoContract]
public class DummyAccTokenPacket
{
[ProtoMember(1)]
public long Token
{
get;
set;
}
}
// ACC_TOKEN // ACC_TOKEN
[ProtoContract] [ProtoContract]
public class AccTokenPacket public class AccTokenPacket
{ {
[ProtoMember(1)] [ProtoMember(1)]
public long Token public string Token
{ {
get; get;
set; set;

View File

@@ -2,6 +2,12 @@ namespace ClientTester.Packet;
public enum PacketCode : ushort public enum PacketCode : ushort
{ {
// ECHO
ECHO = 1000,
// DUMMY 클라는 이걸로 jwt토큰 안받음
DUMMY_ACC_TOKEN = 1001,
// 초기 클라이언트 시작시 jwt토큰 받아옴 // 초기 클라이언트 시작시 jwt토큰 받아옴
ACC_TOKEN = 1, ACC_TOKEN = 1,

View File

@@ -11,7 +11,7 @@ namespace ClientTester.Packet
public static byte[] Serialize<T>(ushort type, T packet) public static byte[] Serialize<T>(ushort type, T packet)
{ {
using MemoryStream payloadMs = new MemoryStream(); using MemoryStream payloadMs = new MemoryStream();
Serializer.Serialize(payloadMs, packet); Serializer.Serialize<T>(payloadMs, packet);
byte[] payload = payloadMs.ToArray(); byte[] payload = payloadMs.ToArray();
ushort size = (ushort)payload.Length; ushort size = (ushort)payload.Length;

View File

@@ -7,7 +7,7 @@ class EcoClientTester
public static readonly string SERVER_IP = "localhost"; public static readonly string SERVER_IP = "localhost";
public static readonly int SERVER_PORT = 9500; public static readonly int SERVER_PORT = 9500;
public static readonly string CONNECTION_KEY = "test"; public static readonly string CONNECTION_KEY = "test";
public static readonly int CLIENT_COUNT = 100; public static readonly int CLIENT_COUNT = 10;
private async Task StartEchoDummyTest() private async Task StartEchoDummyTest()
{ {

View File

@@ -0,0 +1,65 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using MMOserver.Utils;
using Serilog;
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);
// 토큰 검증 - 성공 시 username 반환
// 401 → 재시도 없이 즉시 null 반환 (토큰 자체가 무효)
// 타임아웃/네트워크 오류 → 최대 MAX_RETRY회 재시도 후 null 반환
public async Task<string?> VerifyTokenAsync(string token)
{
for (int attempt = 1; attempt <= MAX_RETRY; attempt++)
{
try
{
HttpResponseMessage response = await httpClient.PostAsJsonAsync(VERIFY_URL, new { token });
// 401: 토큰 자체가 무효 → 재시도해도 같은 결과, 즉시 반환
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Log.Warning("[RestApi] 토큰 인증 실패 (401)");
return null;
}
response.EnsureSuccessStatusCode();
AuthVerifyResponse? result = await response.Content.ReadFromJsonAsync<AuthVerifyResponse>();
return result?.Username;
}
catch (Exception ex) when (attempt < MAX_RETRY)
{
// 일시적 장애 (타임아웃, 네트워크 오류 등) → 재시도
Log.Warning("[RestApi] 통신 실패 (시도 {Attempt}/{Max}): {Message}", attempt, MAX_RETRY, ex.Message);
await Task.Delay(RETRY_DELAY);
}
catch (Exception ex)
{
// 마지막 시도까지 실패
Log.Error("[RestApi] 최종 통신 실패 ({Max}회 시도): {Message}", MAX_RETRY, ex.Message);
}
}
return null;
}
private sealed class AuthVerifyResponse
{
[JsonPropertyName("username")]
public string? Username
{
get;
set;
}
}
}

View File

@@ -21,7 +21,7 @@ public class ChannelManager
public void Initializer(int channelSize = 1) public void Initializer(int channelSize = 1)
{ {
for (int i = 0; i < channelSize; i++) for (int i = 0; i <= channelSize; i++)
{ {
channels.Add(new Channel(i)); channels.Add(new Channel(i));
} }
@@ -40,7 +40,7 @@ public class ChannelManager
public void AddUser(int channelId, long userId, Player player) public void AddUser(int channelId, long userId, Player player)
{ {
// 유저 추가 // 유저 추가
connectUsers[userId] = channelId; connectUsers.Add(userId, channelId);
// 채널에 유저 추가 // 채널에 유저 추가
channels[channelId].AddUser(userId, player); channels[channelId].AddUser(userId, player);
} }

View File

@@ -1,6 +1,9 @@
using LiteNetLib; using LiteNetLib;
using LiteNetLib.Utils;
using MMOserver.Api;
using MMOserver.Game.Channel; using MMOserver.Game.Channel;
using MMOserver.Packet; using MMOserver.Packet;
using MMOserver.Utils;
using ProtoBuf; using ProtoBuf;
using Serilog; using Serilog;
using ServerLib.Packet; using ServerLib.Packet;
@@ -24,6 +27,103 @@ public class GameServer : ServerBase
}; };
} }
protected override void HandleEcho(NetPeer peer, byte[] payload)
{
if (payload.Length < 4)
{
Log.Warning("[Server] Echo 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
return;
}
// 세션에 넣지는 않는다.
NetDataReader reader = new NetDataReader(payload);
short code = reader.GetShort();
short bodyLength = reader.GetShort();
EchoPacket echoPacket = Serializer.Deserialize<EchoPacket>(payload.AsMemory(4));
Log.Debug("[Echo] : addr={Addr}, str={Str}", peer.Address, echoPacket.Str);
// Echo메시지는 순서보장 안함 HOL Blocking 제거
SendTo(peer, payload, DeliveryMethod.ReliableUnordered);
}
protected override void HandleAuthDummy(NetPeer peer, byte[] payload)
{
DummyAccTokenPacket accTokenPacket = Serializer.Deserialize<DummyAccTokenPacket>(new ReadOnlyMemory<byte>(payload));
long hashKey = accTokenPacket.Token;
if (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();
}
peer.Tag = new Session(hashKey, peer);
sessions[hashKey] = peer;
pendingPeers.Remove(peer.Id);
if (hashKey <= 1000)
{
// 더미 클라다.
ChannelManager cm = ChannelManager.Instance;
cm.AddUser(1, hashKey, new Player());
}
else
{
Log.Error("[Server] Dummy 클라이언트가 아닙니다. 연결을 종료합니다. HashKey={Key} PeerId={Id}", hashKey, peer.Id);
peer.Disconnect();
return;
}
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
OnSessionConnected(peer, hashKey);
}
protected override async void HandleAuth(NetPeer peer, byte[] payload)
{
AccTokenPacket accTokenPacket = Serializer.Deserialize<AccTokenPacket>(new ReadOnlyMemory<byte>(payload));
string token = accTokenPacket.Token;
tokenHash.TryGetValue(token, out long hashKey);
if (hashKey <= 1000)
{
hashKey = UuidGeneratorManager.Instance.Create();
}
if (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();
}
else
{
// 신규 연결: 웹서버에 JWT 검증 요청
string? username = await RestApi.Instance.VerifyTokenAsync(token);
if (username == null)
{
Log.Warning("[Server] 토큰 검증 실패 - 연결 거부 PeerId={Id}", peer.Id);
UuidGeneratorManager.Instance.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;
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, long hashKey) protected override void OnSessionConnected(NetPeer peer, long hashKey)
{ {
Log.Information("[GameServer] 세션 연결 HashKey={Key} PeerId={Id}", hashKey, peer.Id); Log.Information("[GameServer] 세션 연결 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
@@ -51,6 +151,7 @@ public class GameServer : ServerBase
{ {
Log.Information("[GameServer] 세션 해제 HashKey={Key} Reason={Reason}", hashKey, info.Reason); Log.Information("[GameServer] 세션 해제 HashKey={Key} Reason={Reason}", hashKey, info.Reason);
} }
UuidGeneratorManager.Instance.Release(hashKey);
} }
protected override void HandlePacket(NetPeer peer, long hashKey, ushort type, byte[] payload) protected override void HandlePacket(NetPeer peer, long hashKey, ushort type, byte[] payload)

View File

@@ -4,6 +4,22 @@ using ProtoBuf;
namespace MMOserver.Packet; namespace MMOserver.Packet;
// ============================================================
// 에코용
// ============================================================
// ECHO
[ProtoContract]
public class EchoPacket
{
[ProtoMember(1)]
public string Str
{
get;
set;
}
}
// ============================================================ // ============================================================
// 공통 타입 // 공통 타입
// ============================================================ // ============================================================
@@ -104,9 +120,21 @@ public class PlayerInfo
// 인증 // 인증
// ============================================================ // ============================================================
// RECV_TOKEN // DUMMY_ACC_TOKEN
[ProtoContract] [ProtoContract]
public class RecvTokenPacket public class DummyAccTokenPacket
{
[ProtoMember(1)]
public long Token
{
get;
set;
}
}
// ACC_TOKEN
[ProtoContract]
public class AccTokenPacket
{ {
[ProtoMember(1)] [ProtoMember(1)]
public string Token public string Token

View File

@@ -2,8 +2,14 @@ namespace MMOserver.Packet;
public enum PacketCode : ushort public enum PacketCode : ushort
{ {
// ECHO
ECHO = 1000,
// DUMMY 클라는 이걸로 jwt토큰 안받음
DUMMY_ACC_TOKEN = 1001,
// 초기 클라이언트 시작시 jwt토큰 받아옴 // 초기 클라이언트 시작시 jwt토큰 받아옴
RECV_TOKEN, ACC_TOKEN = 1,
// 내 정보 로드 (서버 -> 클라) // 내 정보 로드 (서버 -> 클라)
LOAD_GAME, LOAD_GAME,

View File

@@ -0,0 +1,12 @@
namespace MMOserver.Utils;
public abstract class Singleton<T> where T : Singleton<T>, new()
{
private static readonly Lazy<T> instance = new Lazy<T>(static () => new T(), LazyThreadSafetyMode.ExecutionAndPublication);
public static T Instance => instance.Value;
protected Singleton()
{
}
}

View File

@@ -0,0 +1,35 @@
namespace MMOserver.Utils;
public class UuidGeneratorManager : Singleton<UuidGeneratorManager>
{
// 0 ~ 1000 은 더미 클라이언트 예약 범위
private const long DUMMY_RANGE_MAX = 1000;
private readonly object idLock = new();
private readonly HashSet<long> usedIds = new();
// 고유 랜덤 long ID 발급 (1001번 이상, 충돌 시 재생성)
public long Create()
{
lock (idLock)
{
long id;
do
{
id = Random.Shared.NextInt64(DUMMY_RANGE_MAX + 1, long.MaxValue);
} while (usedIds.Contains(id));
usedIds.Add(id);
return id;
}
}
// 로그아웃 / 세션 만료 시 ID 반납
public bool Release(long id)
{
lock (idLock)
{
return usedIds.Remove(id);
}
}
}

View File

@@ -43,7 +43,7 @@ namespace ServerLib.Packet
// 헤더에 명시된 size와 실제 데이터 길이 검증 // 헤더에 명시된 size와 실제 데이터 길이 검증
int actualPayloadLen = data.Length - 4; int actualPayloadLen = data.Length - 4;
if (size > actualPayloadLen) if (size != actualPayloadLen)
{ {
Log.Warning("[PacketSerializer] 페이로드 크기 불일치 HeaderSize={Size} ActualSize={Actual}", size, actualPayloadLen); Log.Warning("[PacketSerializer] 페이로드 크기 불일치 HeaderSize={Size} ActualSize={Actual}", size, actualPayloadLen);
return (0, 0, null)!; return (0, 0, null)!;

View File

@@ -6,6 +6,7 @@ namespace ServerLib.Packet;
/// </summary> /// </summary>
public enum PacketType : ushort public enum PacketType : ushort
{ {
Auth = 1, // 클라 → 서버: 최초 인증 (HashKey 전달) ACC_TOKEN = 1, // 클라 → 서버: 최초 인증 (HashKey 전달)
DUMMY_ACC_TOKEN = 1001,
// 1000번 이상은 게임 패킷으로 예약 // 1000번 이상은 게임 패킷으로 예약
} }

View File

@@ -30,12 +30,15 @@ public abstract class ServerBase : INetEventListener
protected NetManager netManager = null!; protected NetManager netManager = null!;
// 인증 전 대기 피어 (peer.Id → NetPeer) // 인증 전 대기 피어 (peer.Id → NetPeer)
private readonly Dictionary<int, NetPeer> pendingPeers = new(); protected readonly Dictionary<int, NetPeer> pendingPeers = new();
// 인증된 세션 (hashKey → NetPeer) 재연결 조회용 // 인증된 세션 (hashKey → NetPeer) 재연결 조회용
// peer → hashKey 역방향은 peer.Tag as Session 으로 대체 // peer → hashKey 역방향은 peer.Tag as Session 으로 대체
protected readonly Dictionary<long, NetPeer> sessions = new(); protected readonly Dictionary<long, NetPeer> sessions = new();
// Token / HashKey 관리
protected readonly Dictionary<string, long> tokenHash = new();
// 재사용 NetDataWriter (단일 스레드 폴링이므로 안전) // 재사용 NetDataWriter (단일 스레드 폴링이므로 안전)
private readonly NetDataWriter cachedWriter = new(); private readonly NetDataWriter cachedWriter = new();
@@ -123,6 +126,12 @@ public abstract class ServerBase : INetEventListener
// (재연결로 이미 교체된 경우엔 건드리지 않음) // (재연결로 이미 교체된 경우엔 건드리지 않음)
if (sessions.TryGetValue(session.HashKey, out NetPeer? current) && current.Id == peer.Id) if (sessions.TryGetValue(session.HashKey, out NetPeer? current) && current.Id == peer.Id)
{ {
// 더미 클라 아니면 token관리
if (!string.IsNullOrEmpty(session.Token))
{
tokenHash.Remove(session.Token);
}
sessions.Remove(session.HashKey); sessions.Remove(session.HashKey);
Log.Information("[Server] 세션 해제 HashKey={Key} Reason={Reason}", session.HashKey, disconnectInfo.Reason); Log.Information("[Server] 세션 해제 HashKey={Key} Reason={Reason}", session.HashKey, disconnectInfo.Reason);
OnSessionDisconnected(peer, session.HashKey, disconnectInfo); OnSessionDisconnected(peer, session.HashKey, disconnectInfo);
@@ -149,18 +158,23 @@ public abstract class ServerBase : INetEventListener
} }
// 0이라면 에코 서버 테스트용 따로 처리 // 0이라면 에코 서버 테스트용 따로 처리
if (type == 0) if (type == 1000)
{ {
HandleEcho(peer, data); HandleEcho(peer, data);
return; return;
} }
// Auth 패킷은 베이스에서 처리 (raw 8-byte long, protobuf 불필요) // Auth 패킷은 베이스에서 처리 (raw 8-byte long, protobuf 불필요)
if (type == (ushort)PacketType.Auth) if (type == (ushort)PacketType.ACC_TOKEN)
{ {
HandleAuth(peer, payload); HandleAuth(peer, payload);
return; return;
} }
else if (type == (ushort)PacketType.DUMMY_ACC_TOKEN)
{
HandleAuthDummy(peer, payload);
return;
}
// 인증된 피어인지 확인 // 인증된 피어인지 확인
if (peer.Tag is not Session session) if (peer.Tag is not Session session)
@@ -202,52 +216,15 @@ public abstract class ServerBase : INetEventListener
// Echo 서버 테스트 // Echo 서버 테스트
private void HandleEcho(NetPeer peer, byte[] payload) protected abstract void HandleEcho(NetPeer peer, byte[] payload);
{
if (payload.Length < 4)
{
Log.Warning("[Server] Echo 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
return;
}
// 세션에 넣지는 않는다. // ─── Auth 처리 (더미) ────────────────────────────────────────────────
NetDataReader reader = new NetDataReader(payload);
short code = reader.GetShort();
short bodyLength = reader.GetShort();
Log.Debug("[Echo] : addr={Addr}, str={Str}", peer.Address, reader.GetString());
// Echo메시지는 순서보장 안함 HOL Blocking 제거
SendTo(peer, payload, DeliveryMethod.ReliableUnordered);
}
// ─── Auth 처리 (내부) ──────────────────────────────────────────────── protected abstract void HandleAuthDummy(NetPeer peer, byte[] payload);
private void HandleAuth(NetPeer peer, byte[] payload) // ─── Auth 처리 ────────────────────────────────────────────────
{
if (payload.Length < sizeof(long))
{
Log.Warning("[Server] Auth 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
peer.Disconnect();
return;
}
long hashKey = BitConverter.ToInt64(payload, 0); protected abstract void HandleAuth(NetPeer peer, byte[] payload);
if (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();
}
peer.Tag = new Session(hashKey, peer);
sessions[hashKey] = peer;
pendingPeers.Remove(peer.Id);
Log.Information("[Server] 인증 완료 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
OnSessionConnected(peer, hashKey);
}
// ─── 전송 헬퍼 ─────────────────────────────────────────────────────── // ─── 전송 헬퍼 ───────────────────────────────────────────────────────

View File

@@ -4,12 +4,28 @@ namespace ServerLib.Service;
public class Session public class Session
{ {
public long HashKey { get; init; } public string? Token
public NetPeer Peer { get; set; } {
get;
set;
}
public long HashKey
{
get;
init;
}
public NetPeer Peer
{
get;
set;
}
public Session(long hashKey, NetPeer peer) public Session(long hashKey, NetPeer peer)
{ {
HashKey = hashKey; HashKey = hashKey;
Peer = peer; Peer = peer;
Token = null;
} }
} }