feat : 맵 바운딩 박스 처리 / echo 패킷 구조 재 구성 / 더미 클라이언트 랜덤 이동 작업

This commit is contained in:
qornwh1
2026-03-04 14:51:43 +09:00
parent 241820846d
commit 053c5d23b9
16 changed files with 262 additions and 121 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
{ {
@@ -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,5 +1,6 @@
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;
@@ -131,12 +132,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;
}
}
// ============================================================ // ============================================================
// 공통 타입 // 공통 타입
// ============================================================ // ============================================================

View File

@@ -2,6 +2,8 @@ namespace ClientTester.Packet;
public enum PacketCode : ushort public enum PacketCode : ushort
{ {
ECHO = 0,
// 초기 클라이언트 시작시 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

@@ -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,4 +1,5 @@
using LiteNetLib; using LiteNetLib;
using LiteNetLib.Utils;
using MMOserver.Game.Channel; using MMOserver.Game.Channel;
using MMOserver.Packet; using MMOserver.Packet;
using ProtoBuf; using ProtoBuf;
@@ -24,6 +25,54 @@ 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 HandleAuth(NetPeer peer, byte[] payload)
{
AccTokenPacket accTokenPacket = Serializer.Deserialize<AccTokenPacket>(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());
}
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);

View File

@@ -30,4 +30,8 @@
<ProjectReference Include="..\ServerLib\ServerLib.csproj" /> <ProjectReference Include="..\ServerLib\ServerLib.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="RestApi\" />
</ItemGroup>
</Project> </Project>

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;
}
}
// ============================================================ // ============================================================
// 공통 타입 // 공통 타입
// ============================================================ // ============================================================

View File

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

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

@@ -30,7 +30,7 @@ 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 으로 대체
@@ -202,52 +202,11 @@ 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;
}
// 세션에 넣지는 않는다.
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 처리 (내부) ────────────────────────────────────────────────
private void HandleAuth(NetPeer peer, byte[] payload) protected abstract 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;
}
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);
}
// ─── 전송 헬퍼 ─────────────────────────────────────────────────────── // ─── 전송 헬퍼 ───────────────────────────────────────────────────────