Compare commits
6 Commits
dummy_test
...
bfa3394ad1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bfa3394ad1 | ||
|
|
c8ce36a624 | ||
|
|
18fd8a0737 | ||
|
|
343ea43a03 | ||
|
|
053c5d23b9 | ||
|
|
241820846d |
@@ -11,10 +11,18 @@ public class DummyClientService
|
||||
// 모든거 강종
|
||||
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;
|
||||
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);
|
||||
}
|
||||
@@ -30,30 +38,23 @@ public class DummyClientService
|
||||
{
|
||||
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, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
await Task.Delay(10);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendLoopAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(500, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
await Task.Delay(500);
|
||||
|
||||
int tick = 0;
|
||||
|
||||
@@ -85,14 +86,7 @@ public class DummyClientService
|
||||
Log.Debug("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total);
|
||||
tick++;
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(sendInterval, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
await Task.Delay(sendInterval);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,9 @@ public class DummyClients
|
||||
private float dirX = 0f;
|
||||
private float dirZ = 0f;
|
||||
|
||||
// 맵 경계
|
||||
public MapBounds Map { get; set; } = new MapBounds(-50f, 50f, -50f, 50f);
|
||||
|
||||
// 통계
|
||||
public int SentCount
|
||||
{
|
||||
@@ -60,10 +63,10 @@ public class DummyClients
|
||||
Log.Information("[Client {ClientId:00}] 연결됨", this.clientId);
|
||||
|
||||
// clientID가 토큰의 hashKey라고 가정함
|
||||
AccTokenPacket recvTokenPacket = new AccTokenPacket();
|
||||
DummyAccTokenPacket recvTokenPacket = new DummyAccTokenPacket();
|
||||
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);
|
||||
peer.Send(writer, DeliveryMethod.ReliableOrdered);
|
||||
writer.Reset();
|
||||
@@ -71,15 +74,6 @@ public class DummyClients
|
||||
|
||||
listener.NetworkReceiveEvent += (peer, reader, channel, deliveryMethod) =>
|
||||
{
|
||||
short code = reader.GetShort();
|
||||
short bodyLength = reader.GetShort();
|
||||
string? msg = reader.GetString();
|
||||
|
||||
if (msg != null)
|
||||
{
|
||||
RttCount++;
|
||||
}
|
||||
|
||||
ReceivedCount++;
|
||||
reader.Recycle();
|
||||
};
|
||||
@@ -104,8 +98,12 @@ public class DummyClients
|
||||
// 남은 거리가 없으면 새 방향·목표 거리 설정
|
||||
if (distance <= 0f)
|
||||
{
|
||||
// 현재 각도에서 -30~+30도 범위로 회전
|
||||
rotY = (rotY + Random.Shared.Next(-30, 31) + 360) % 360;
|
||||
// 벽에 붙어있으면 반대 방향 강제, 아니면 ±30도 회전
|
||||
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;
|
||||
dirX = MathF.Sin(rad);
|
||||
dirZ = MathF.Cos(rad);
|
||||
@@ -117,9 +115,14 @@ public class DummyClients
|
||||
|
||||
// 이번 틱 이동량 (남은 거리 초과 방지)
|
||||
float step = MathF.Min(moveSpeed * delta, distance);
|
||||
posX += dirX * step;
|
||||
posZ += dirZ * step;
|
||||
distance -= step;
|
||||
float nextX = posX + dirX * step;
|
||||
float nextZ = posZ + dirZ * step;
|
||||
|
||||
// 벽 충돌 시 clamp + 다음 틱에 방향 재설정
|
||||
bool hitWall = Map.Clamp(ref nextX, ref nextZ);
|
||||
posX = nextX;
|
||||
posZ = nextZ;
|
||||
distance = hitWall ? 0f : distance - step;
|
||||
|
||||
// 정수 Vector3 갱신
|
||||
position.X = (int)MathF.Round(posX);
|
||||
|
||||
116
ClientTester/EchoClientTester/DummyService/MapBounds.cs
Normal file
116
ClientTester/EchoClientTester/DummyService/MapBounds.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -59,27 +59,13 @@ public class EchoDummyClientService
|
||||
c.PollEvents();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(10, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
await Task.Delay(10);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendLoopAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(500, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
await Task.Delay(500);
|
||||
|
||||
int tick = 0;
|
||||
|
||||
@@ -111,14 +97,7 @@ public class EchoDummyClientService
|
||||
Log.Debug("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total);
|
||||
tick++;
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(sendInterval, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
await Task.Delay(sendInterval);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using ClientTester.Packet;
|
||||
using LiteNetLib;
|
||||
using LiteNetLib.Utils;
|
||||
using ProtoBuf;
|
||||
using Serilog;
|
||||
|
||||
namespace ClientTester.EchoDummyService;
|
||||
@@ -75,10 +77,14 @@ public class EchoDummyClients
|
||||
{
|
||||
short code = 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;
|
||||
|
||||
if (msg != null && msg.StartsWith("Echo seq:") &&
|
||||
if (msg.StartsWith("Echo seq:") &&
|
||||
int.TryParse(msg.Substring("Echo seq:".Length), out int seq) &&
|
||||
pendingPings.TryRemove(seq, out sentTick))
|
||||
{
|
||||
@@ -131,12 +137,12 @@ public class EchoDummyClients
|
||||
}
|
||||
}
|
||||
|
||||
PacketHeader packetHeader = new PacketHeader();
|
||||
packetHeader.Code = 0;
|
||||
packetHeader.BodyLength = (ushort)$"Echo seq:{seq}".Length;
|
||||
writer.Put((short)packetHeader.Code);
|
||||
writer.Put((short)packetHeader.BodyLength);
|
||||
writer.Put($"Echo seq:{seq}");
|
||||
// string → raw bytes (길이 prefix 방지)
|
||||
EchoPacket echoPacket = new EchoPacket();
|
||||
echoPacket.Str = $"Echo seq:{seq}";
|
||||
|
||||
byte[] data = PacketSerializer.Serialize<EchoPacket>((ushort)PacketCode.ECHO, echoPacket);
|
||||
writer.Put(data);
|
||||
// 순서보장 안함 HOL Blocking 제거
|
||||
peer.Send(writer, DeliveryMethod.ReliableUnordered);
|
||||
SentCount++;
|
||||
|
||||
@@ -4,6 +4,22 @@ using ProtoBuf;
|
||||
|
||||
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
|
||||
[ProtoContract]
|
||||
public class AccTokenPacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public long Token
|
||||
public string Token
|
||||
{
|
||||
get;
|
||||
set;
|
||||
|
||||
@@ -2,6 +2,12 @@ namespace ClientTester.Packet;
|
||||
|
||||
public enum PacketCode : ushort
|
||||
{
|
||||
// ECHO
|
||||
ECHO = 1000,
|
||||
|
||||
// DUMMY 클라는 이걸로 jwt토큰 안받음
|
||||
DUMMY_ACC_TOKEN = 1001,
|
||||
|
||||
// 초기 클라이언트 시작시 jwt토큰 받아옴
|
||||
ACC_TOKEN = 1,
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ namespace ClientTester.Packet
|
||||
public static byte[] Serialize<T>(ushort type, T packet)
|
||||
{
|
||||
using MemoryStream payloadMs = new MemoryStream();
|
||||
Serializer.Serialize(payloadMs, packet);
|
||||
Serializer.Serialize<T>(payloadMs, packet);
|
||||
byte[] payload = payloadMs.ToArray();
|
||||
ushort size = (ushort)payload.Length;
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ class EcoClientTester
|
||||
public static readonly string SERVER_IP = "localhost";
|
||||
public static readonly int SERVER_PORT = 9500;
|
||||
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()
|
||||
{
|
||||
|
||||
65
MMOTestServer/MMOserver/Api/RestApi.cs
Normal file
65
MMOTestServer/MMOserver/Api/RestApi.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ public class ChannelManager
|
||||
|
||||
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));
|
||||
}
|
||||
@@ -40,7 +40,7 @@ public class ChannelManager
|
||||
public void AddUser(int channelId, long userId, Player player)
|
||||
{
|
||||
// 유저 추가
|
||||
connectUsers[userId] = channelId;
|
||||
connectUsers.Add(userId, channelId);
|
||||
// 채널에 유저 추가
|
||||
channels[channelId].AddUser(userId, player);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
using LiteNetLib;
|
||||
using LiteNetLib.Utils;
|
||||
using MMOserver.Api;
|
||||
using MMOserver.Game.Channel;
|
||||
using MMOserver.Packet;
|
||||
using MMOserver.Utils;
|
||||
using ProtoBuf;
|
||||
using Serilog;
|
||||
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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
UuidGeneratorManager.Instance.Release(hashKey);
|
||||
}
|
||||
|
||||
protected override void HandlePacket(NetPeer peer, long hashKey, ushort type, byte[] payload)
|
||||
|
||||
@@ -4,6 +4,22 @@ using ProtoBuf;
|
||||
|
||||
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]
|
||||
public class RecvTokenPacket
|
||||
public class DummyAccTokenPacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public long Token
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
// ACC_TOKEN
|
||||
[ProtoContract]
|
||||
public class AccTokenPacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public string Token
|
||||
|
||||
@@ -2,8 +2,14 @@ namespace MMOserver.Packet;
|
||||
|
||||
public enum PacketCode : ushort
|
||||
{
|
||||
// ECHO
|
||||
ECHO = 1000,
|
||||
|
||||
// DUMMY 클라는 이걸로 jwt토큰 안받음
|
||||
DUMMY_ACC_TOKEN = 1001,
|
||||
|
||||
// 초기 클라이언트 시작시 jwt토큰 받아옴
|
||||
RECV_TOKEN,
|
||||
ACC_TOKEN = 1,
|
||||
|
||||
// 내 정보 로드 (서버 -> 클라)
|
||||
LOAD_GAME,
|
||||
|
||||
12
MMOTestServer/MMOserver/Utils/Singleton.cs
Normal file
12
MMOTestServer/MMOserver/Utils/Singleton.cs
Normal 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()
|
||||
{
|
||||
}
|
||||
}
|
||||
35
MMOTestServer/MMOserver/Utils/UuidGeneratorManager.cs
Normal file
35
MMOTestServer/MMOserver/Utils/UuidGeneratorManager.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,7 @@ namespace ServerLib.Packet
|
||||
|
||||
// 헤더에 명시된 size와 실제 데이터 길이 검증
|
||||
int actualPayloadLen = data.Length - 4;
|
||||
if (size > actualPayloadLen)
|
||||
if (size != actualPayloadLen)
|
||||
{
|
||||
Log.Warning("[PacketSerializer] 페이로드 크기 불일치 HeaderSize={Size} ActualSize={Actual}", size, actualPayloadLen);
|
||||
return (0, 0, null)!;
|
||||
|
||||
@@ -6,6 +6,7 @@ namespace ServerLib.Packet;
|
||||
/// </summary>
|
||||
public enum PacketType : ushort
|
||||
{
|
||||
Auth = 1, // 클라 → 서버: 최초 인증 (HashKey 전달)
|
||||
ACC_TOKEN = 1, // 클라 → 서버: 최초 인증 (HashKey 전달)
|
||||
DUMMY_ACC_TOKEN = 1001,
|
||||
// 1000번 이상은 게임 패킷으로 예약
|
||||
}
|
||||
|
||||
@@ -30,12 +30,15 @@ public abstract class ServerBase : INetEventListener
|
||||
protected NetManager netManager = null!;
|
||||
|
||||
// 인증 전 대기 피어 (peer.Id → NetPeer)
|
||||
private readonly Dictionary<int, NetPeer> pendingPeers = new();
|
||||
protected readonly Dictionary<int, NetPeer> pendingPeers = new();
|
||||
|
||||
// 인증된 세션 (hashKey → NetPeer) 재연결 조회용
|
||||
// peer → hashKey 역방향은 peer.Tag as Session 으로 대체
|
||||
protected readonly Dictionary<long, NetPeer> sessions = new();
|
||||
|
||||
// Token / HashKey 관리
|
||||
protected readonly Dictionary<string, long> tokenHash = new();
|
||||
|
||||
// 재사용 NetDataWriter (단일 스레드 폴링이므로 안전)
|
||||
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)
|
||||
{
|
||||
// 더미 클라 아니면 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);
|
||||
@@ -149,18 +158,23 @@ public abstract class ServerBase : INetEventListener
|
||||
}
|
||||
|
||||
// 0이라면 에코 서버 테스트용 따로 처리
|
||||
if (type == 0)
|
||||
if (type == 1000)
|
||||
{
|
||||
HandleEcho(peer, data);
|
||||
return;
|
||||
}
|
||||
|
||||
// Auth 패킷은 베이스에서 처리 (raw 8-byte long, protobuf 불필요)
|
||||
if (type == (ushort)PacketType.Auth)
|
||||
if (type == (ushort)PacketType.ACC_TOKEN)
|
||||
{
|
||||
HandleAuth(peer, payload);
|
||||
return;
|
||||
}
|
||||
else if (type == (ushort)PacketType.DUMMY_ACC_TOKEN)
|
||||
{
|
||||
HandleAuthDummy(peer, payload);
|
||||
return;
|
||||
}
|
||||
|
||||
// 인증된 피어인지 확인
|
||||
if (peer.Tag is not Session session)
|
||||
@@ -202,52 +216,15 @@ public abstract class ServerBase : INetEventListener
|
||||
|
||||
// Echo 서버 테스트
|
||||
|
||||
private void HandleEcho(NetPeer peer, byte[] payload)
|
||||
{
|
||||
if (payload.Length < 4)
|
||||
{
|
||||
Log.Warning("[Server] Echo 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
|
||||
return;
|
||||
}
|
||||
protected abstract void HandleEcho(NetPeer peer, byte[] payload);
|
||||
|
||||
// 세션에 넣지는 않는다.
|
||||
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 처리 (더미) ────────────────────────────────────────────────
|
||||
|
||||
// ─── Auth 처리 (내부) ────────────────────────────────────────────────
|
||||
protected abstract void HandleAuthDummy(NetPeer peer, byte[] payload);
|
||||
|
||||
private void HandleAuth(NetPeer peer, byte[] payload)
|
||||
{
|
||||
if (payload.Length < sizeof(long))
|
||||
{
|
||||
Log.Warning("[Server] Auth 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
|
||||
peer.Disconnect();
|
||||
return;
|
||||
}
|
||||
// ─── Auth 처리 ────────────────────────────────────────────────
|
||||
|
||||
long hashKey = BitConverter.ToInt64(payload, 0);
|
||||
|
||||
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);
|
||||
}
|
||||
protected abstract void HandleAuth(NetPeer peer, byte[] payload);
|
||||
|
||||
// ─── 전송 헬퍼 ───────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -4,12 +4,28 @@ namespace ServerLib.Service;
|
||||
|
||||
public class Session
|
||||
{
|
||||
public long HashKey { get; init; }
|
||||
public NetPeer Peer { get; set; }
|
||||
public string? Token
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public long HashKey
|
||||
{
|
||||
get;
|
||||
init;
|
||||
}
|
||||
|
||||
public NetPeer Peer
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public Session(long hashKey, NetPeer peer)
|
||||
{
|
||||
HashKey = hashKey;
|
||||
Peer = peer;
|
||||
Peer = peer;
|
||||
Token = null;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user