Files
a301_mmo_game_server/ClientTester/EchoClientTester/EchoDummyService/EchoDummyClientService.cs

157 lines
4.3 KiB
C#

using LiteNetLib;
using Serilog;
namespace ClientTester.EchoDummyService;
public class EchoDummyClientService
{
private readonly List<EchoDummyClients> clients;
private readonly int sendInterval;
// 유닛 테스트용 (n패킷 시간체크)
public bool IsTest
{
get;
set;
} = false;
public int TestCount
{
get;
set;
} = 100000;
// 모든거 강종
public event Action? OnAllDisconnected;
public EchoDummyClientService(int count, string ip, int port, string key, int sendIntervalMs = 1000)
{
sendInterval = sendIntervalMs;
clients = Enumerable.Range(0, count).Select(i => new EchoDummyClients(i, ip, port, key)).ToList();
Log.Information("[SERVICE] {Count}개 클라이언트 생성 → {Ip}:{Port}", count, ip, port);
}
public async Task RunAsync(CancellationToken ct)
{
if (IsTest)
{
foreach (EchoDummyClients c in clients)
{
c.TestCount = TestCount;
}
Log.Information("[TEST] 유닛 테스트 모드: 클라이언트당 {Count}개 수신 시 자동 종료", TestCount);
}
await Task.WhenAll(
PollLoopAsync(ct),
SendLoopAsync(ct)
);
}
private async Task PollLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
foreach (EchoDummyClients c in clients)
{
c.PollEvents();
}
await Task.Delay(10);
}
}
private async Task SendLoopAsync(CancellationToken ct)
{
await Task.Delay(500);
int tick = 0;
while (!ct.IsCancellationRequested)
{
int sent = 0;
int total = clients.Count;
foreach (EchoDummyClients client in clients)
{
client.SendPing();
if (client.peer != null)
{
sent++;
}
else
{
total--;
}
}
if (total == 0)
{
Log.Information("All Disconnect Clients");
OnAllDisconnected?.Invoke();
break;
}
Log.Debug("[TICK {Tick:000}] {Sent}/{Total} 전송", tick, sent, total);
tick++;
await Task.Delay(sendInterval);
}
}
public void PrintStats()
{
int totalSent = 0, totalRecv = 0;
int connected = 0;
int rttClientCount = 0;
Log.Information("───────────── Performance Report ─────────────");
double totalAvgRtt = 0;
foreach (EchoDummyClients c in clients)
{
NetStatistics? stats = c.peer?.Statistics;
long loss = stats?.PacketLoss ?? 0;
float lossPct = stats?.PacketLossPercent ?? 0f;
Log.Information(
"[Client {ClientId:00}] Sent={Sent} Recv={Recv} | Loss={Loss}({LossPct:F1}%) AvgRTT={AvgRtt:F3}ms LastRTT={LastRtt:F3}ms",
c.clientId, c.SentCount, c.ReceivedCount, loss, lossPct, c.AvgRttMs, c.LastRttMs);
totalSent += c.SentCount;
totalRecv += c.ReceivedCount;
if (c.RttCount > 0)
{
totalAvgRtt += c.AvgRttMs;
rttClientCount++;
}
if (c.peer != null)
{
connected++;
}
}
double avgRtt = rttClientCount > 0 ? totalAvgRtt / rttClientCount : 0;
Log.Information("────────────────────────────────────────────");
Log.Information(
"[TOTAL] Sent={Sent} Recv={Recv} Connected={Connected}/{Total} AvgRTT={AvgRtt:F3}ms",
totalSent, totalRecv, connected, clients.Count, avgRtt);
Log.Information("────────────────────────────────────────────");
}
public void Stop()
{
foreach (EchoDummyClients c in clients)
{
c.Stop();
}
Log.Information("[SERVICE] 모든 클라이언트 종료됨.");
}
}