Compare commits
9 Commits
d73487df5b
...
multi_test
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d2ba2ccb48 | ||
|
|
27f3832894 | ||
|
|
f75d71c1ee | ||
|
|
a9e1d2acaf | ||
|
|
e3f365877b | ||
|
|
01d107def3 | ||
| 6f164b6cdb | |||
| f3eaeac37b | |||
| cf2be6b125 |
@@ -8,6 +8,19 @@ public class DummyClientService
|
||||
private readonly List<DummyClients> clients;
|
||||
private readonly int sendInterval;
|
||||
|
||||
// 유닛 테스트용 (n패킷 시간체크)
|
||||
public bool IsTest
|
||||
{
|
||||
get;
|
||||
set;
|
||||
} = false;
|
||||
|
||||
public int TestCount
|
||||
{
|
||||
get;
|
||||
set;
|
||||
} = 100000;
|
||||
|
||||
// 모든거 강종
|
||||
public event Action? OnAllDisconnected;
|
||||
|
||||
@@ -21,6 +34,16 @@ public class DummyClientService
|
||||
|
||||
public async Task RunAsync(CancellationToken ct)
|
||||
{
|
||||
if (IsTest)
|
||||
{
|
||||
foreach (DummyClients c in clients)
|
||||
{
|
||||
c.TestCount = TestCount;
|
||||
}
|
||||
|
||||
Log.Information("[TEST] 유닛 테스트 모드: 클라이언트당 {Count}개 수신 시 자동 종료", TestCount);
|
||||
}
|
||||
|
||||
await Task.WhenAll(
|
||||
PollLoopAsync(ct),
|
||||
SendLoopAsync(ct)
|
||||
@@ -103,6 +126,7 @@ public class DummyClientService
|
||||
{
|
||||
int totalSent = 0, totalRecv = 0;
|
||||
int connected = 0;
|
||||
int rttClientCount = 0;
|
||||
|
||||
Log.Information("───────────── Performance Report ─────────────");
|
||||
|
||||
@@ -120,14 +144,18 @@ public class DummyClientService
|
||||
|
||||
totalSent += c.SentCount;
|
||||
totalRecv += c.ReceivedCount;
|
||||
if (c.RttCount > 0)
|
||||
{
|
||||
totalAvgRtt += c.AvgRttMs;
|
||||
rttClientCount++;
|
||||
}
|
||||
if (c.peer != null)
|
||||
{
|
||||
connected++;
|
||||
}
|
||||
}
|
||||
|
||||
double avgRtt = connected > 0 ? totalAvgRtt / connected : 0;
|
||||
double avgRtt = rttClientCount > 0 ? totalAvgRtt / rttClientCount : 0;
|
||||
|
||||
Log.Information("────────────────────────────────────────────");
|
||||
Log.Information(
|
||||
|
||||
@@ -18,6 +18,14 @@ public class DummyClients
|
||||
// seq → 송신 타임스탬프 (Stopwatch tick)
|
||||
private ConcurrentDictionary<int, long> pendingPings = new();
|
||||
private int seqNumber;
|
||||
private const int MaxPendingPings = 1000;
|
||||
|
||||
// 유닛 테스트용 (0 = 제한 없음)
|
||||
public int TestCount
|
||||
{
|
||||
get;
|
||||
set;
|
||||
} = 0;
|
||||
|
||||
// 통계
|
||||
public int SentCount
|
||||
@@ -81,6 +89,12 @@ public class DummyClients
|
||||
}
|
||||
|
||||
ReceivedCount++;
|
||||
|
||||
if (TestCount > 0 && ReceivedCount >= TestCount)
|
||||
{
|
||||
peer.Disconnect();
|
||||
}
|
||||
|
||||
reader.Recycle();
|
||||
};
|
||||
|
||||
@@ -104,9 +118,20 @@ public class DummyClients
|
||||
int seq = seqNumber++;
|
||||
pendingPings[seq] = Stopwatch.GetTimestamp();
|
||||
|
||||
// 응답 없는 오래된 ping 정리 (패킷 유실 시 메모리 누수 방지)
|
||||
if (pendingPings.Count > MaxPendingPings)
|
||||
{
|
||||
int cutoff = seq - MaxPendingPings;
|
||||
foreach (int key in pendingPings.Keys)
|
||||
{
|
||||
if (key < cutoff)
|
||||
pendingPings.TryRemove(key, out _);
|
||||
}
|
||||
}
|
||||
|
||||
PacketHeader packetHeader = new PacketHeader();
|
||||
packetHeader.Code = 0;
|
||||
packetHeader.BodyLength = $"seq:{seq}".Length;
|
||||
packetHeader.BodyLength = $"Echo seq:{seq}".Length;
|
||||
writer.Put((short)packetHeader.Code);
|
||||
writer.Put((short)packetHeader.BodyLength);
|
||||
writer.Put($"Echo seq:{seq}");
|
||||
|
||||
@@ -7,22 +7,21 @@ namespace ClientTester.Packet
|
||||
|
||||
public static class PacketSerializer
|
||||
{
|
||||
// 직렬화: 객체 → byte[]
|
||||
public static byte[] Serialize<T>(ushort type, ushort size, T packet)
|
||||
// 직렬화: 객체 → byte[] (size는 payload 크기로 자동 계산)
|
||||
public static byte[] Serialize<T>(ushort type, T packet)
|
||||
{
|
||||
MemoryStream ms = new MemoryStream();
|
||||
using MemoryStream payloadMs = new MemoryStream();
|
||||
Serializer.Serialize(payloadMs, packet);
|
||||
byte[] payload = payloadMs.ToArray();
|
||||
ushort size = (ushort)payload.Length;
|
||||
|
||||
// 2바이트 패킷 타입 헤더
|
||||
ms.WriteByte((byte)(type & 0xFF));
|
||||
ms.WriteByte((byte)(type >> 8));
|
||||
|
||||
// 2바이트 패킷 길이 헤더
|
||||
ms.WriteByte((byte)(size & 0xFF));
|
||||
ms.WriteByte((byte)(size >> 8));
|
||||
|
||||
// protobuf 페이로드
|
||||
Serializer.Serialize(ms, packet);
|
||||
return ms.ToArray();
|
||||
byte[] result = new byte[4 + payload.Length];
|
||||
result[0] = (byte)(type & 0xFF);
|
||||
result[1] = (byte)(type >> 8);
|
||||
result[2] = (byte)(size & 0xFF);
|
||||
result[3] = (byte)(size >> 8);
|
||||
Buffer.BlockCopy(payload, 0, result, 4, payload.Length);
|
||||
return result;
|
||||
}
|
||||
|
||||
// 역직렬화: byte[] → (PacketType, payload bytes)
|
||||
@@ -34,19 +33,25 @@ namespace ClientTester.Packet
|
||||
return (0, 0, null)!;
|
||||
}
|
||||
|
||||
// 길이체크도 필요함
|
||||
|
||||
ushort type = (ushort)(data[0] | (data[1] << 8));
|
||||
ushort size = (ushort)(data[2] | (data[3] << 8));
|
||||
byte[] payload = new byte[data.Length - 4];
|
||||
Buffer.BlockCopy(data, 4, payload, 0, payload.Length);
|
||||
|
||||
int actualPayloadLen = data.Length - 4;
|
||||
if (size > actualPayloadLen)
|
||||
{
|
||||
Log.Warning("[PacketSerializer] 페이로드 크기 불일치 HeaderSize={Size} ActualSize={Actual}", size, actualPayloadLen);
|
||||
return (0, 0, null)!;
|
||||
}
|
||||
|
||||
byte[] payload = new byte[size];
|
||||
Buffer.BlockCopy(data, 4, payload, 0, size);
|
||||
return (type, size, payload);
|
||||
}
|
||||
|
||||
// 페이로드 → 특정 타입으로 역직렬화
|
||||
public static T DeserializePayload<T>(byte[] payload)
|
||||
{
|
||||
MemoryStream ms = new MemoryStream(payload);
|
||||
using MemoryStream ms = new MemoryStream(payload);
|
||||
return Serializer.Deserialize<T>(ms);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ using Serilog;
|
||||
|
||||
class EcoClientTester
|
||||
{
|
||||
public static readonly string SERVER_IP = "localhost";
|
||||
public static readonly string SERVER_IP = "tolelom.xyz";
|
||||
public static readonly int SERVER_PORT = 9500;
|
||||
public static readonly string CONNECTION_KEY = "test";
|
||||
public static readonly int CLIENT_COUNT = 100;
|
||||
@@ -29,12 +29,14 @@ class EcoClientTester
|
||||
};
|
||||
|
||||
DummyClientService service = new DummyClientService(CLIENT_COUNT, SERVER_IP, SERVER_PORT, CONNECTION_KEY, 100);
|
||||
service.OnAllDisconnected += async () =>
|
||||
service.OnAllDisconnected += () =>
|
||||
{
|
||||
Log.Warning("[SHUTDOWN] 종료 이벤트 발생, 종료 중...");
|
||||
await cts.CancelAsync();
|
||||
cts.Cancel();
|
||||
};
|
||||
|
||||
// service.IsTest = true;
|
||||
// service.TestCount = 100;
|
||||
await service.RunAsync(cts.Token);
|
||||
|
||||
service.PrintStats();
|
||||
|
||||
82
MMOTestServer/MMOserver/Game/Channel/Channel.cs
Normal file
82
MMOTestServer/MMOserver/Game/Channel/Channel.cs
Normal file
@@ -0,0 +1,82 @@
|
||||
using MMOserver.Game.Channel.Maps;
|
||||
|
||||
namespace MMOserver.Game.Channel;
|
||||
|
||||
public class Channel
|
||||
{
|
||||
// 로비
|
||||
private Robby robby = new Robby();
|
||||
|
||||
// 채널 내 유저 상태 (hashKey → Player)
|
||||
private Dictionary<long, Player> connectUsers = new Dictionary<long, Player>();
|
||||
|
||||
public int ChannelId
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
public int UserCount
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
public int UserCountMax
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
} = 100;
|
||||
|
||||
public Channel(int channelId)
|
||||
{
|
||||
ChannelId = channelId;
|
||||
}
|
||||
|
||||
public void AddUser(long userId, Player player)
|
||||
{
|
||||
connectUsers[userId] = player;
|
||||
UserCount++;
|
||||
}
|
||||
|
||||
public void RemoveUser(long userId)
|
||||
{
|
||||
connectUsers.Remove(userId);
|
||||
UserCount--;
|
||||
}
|
||||
|
||||
// 채널 내 모든 유저의 hashKey 반환
|
||||
public IEnumerable<long> GetConnectUsers()
|
||||
{
|
||||
return connectUsers.Keys;
|
||||
}
|
||||
|
||||
// 채널 내 모든 Player 반환
|
||||
public IEnumerable<Player> GetPlayers()
|
||||
{
|
||||
return connectUsers.Values;
|
||||
}
|
||||
|
||||
// 특정 유저의 Player 반환
|
||||
public Player? GetPlayer(long userId)
|
||||
{
|
||||
connectUsers.TryGetValue(userId, out Player? player);
|
||||
return player;
|
||||
}
|
||||
|
||||
public int HasUser(long userId)
|
||||
{
|
||||
if (connectUsers.ContainsKey(userId))
|
||||
{
|
||||
return ChannelId;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 로비 가져옴
|
||||
public Robby GetRobby()
|
||||
{
|
||||
return robby;
|
||||
}
|
||||
}
|
||||
84
MMOTestServer/MMOserver/Game/Channel/ChannelManager.cs
Normal file
84
MMOTestServer/MMOserver/Game/Channel/ChannelManager.cs
Normal file
@@ -0,0 +1,84 @@
|
||||
namespace MMOserver.Game.Channel;
|
||||
|
||||
public class ChannelManager
|
||||
{
|
||||
// 일단은 채널은 서버 켤때 고정으로간다 1개
|
||||
public static ChannelManager Instance
|
||||
{
|
||||
get;
|
||||
} = new ChannelManager();
|
||||
|
||||
// 채널 관리
|
||||
private List<Channel> channels = new List<Channel>();
|
||||
|
||||
// 채널별 유저 관리 (유저 key, 채널 val)
|
||||
private Dictionary<long, int> connectUsers = new Dictionary<long, int>();
|
||||
|
||||
public ChannelManager()
|
||||
{
|
||||
Initializer();
|
||||
}
|
||||
|
||||
public void Initializer(int channelSize = 1)
|
||||
{
|
||||
for (int i = 0; i < channelSize; i++)
|
||||
{
|
||||
channels.Add(new Channel(i));
|
||||
}
|
||||
}
|
||||
|
||||
public Channel GetChannel(int channelId)
|
||||
{
|
||||
return channels[channelId];
|
||||
}
|
||||
|
||||
public List<Channel> GetChannels()
|
||||
{
|
||||
return channels;
|
||||
}
|
||||
|
||||
public void AddUser(int channelId, long userId, Player player)
|
||||
{
|
||||
// 유저 추가
|
||||
connectUsers[userId] = channelId;
|
||||
// 채널에 유저 추가
|
||||
channels[channelId].AddUser(userId, player);
|
||||
}
|
||||
|
||||
public bool RemoveUser(long userId)
|
||||
{
|
||||
// 채널 있으면
|
||||
int channelId = connectUsers[userId];
|
||||
|
||||
// 날린다.
|
||||
if (channelId >= 0)
|
||||
{
|
||||
channels[channelId].RemoveUser(userId);
|
||||
connectUsers.Remove(userId);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public int HasUser(long userId)
|
||||
{
|
||||
int channelId = -1;
|
||||
if (connectUsers.ContainsKey(userId))
|
||||
{
|
||||
channelId = connectUsers[userId];
|
||||
}
|
||||
|
||||
if (channelId != -1)
|
||||
{
|
||||
return channels[channelId].HasUser(userId);
|
||||
}
|
||||
|
||||
return channelId;
|
||||
}
|
||||
|
||||
public Dictionary<long, int> GetConnectUsers()
|
||||
{
|
||||
return connectUsers;
|
||||
}
|
||||
}
|
||||
17
MMOTestServer/MMOserver/Game/Channel/Maps/Robby.cs
Normal file
17
MMOTestServer/MMOserver/Game/Channel/Maps/Robby.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using MMOserver.Game.Engine;
|
||||
|
||||
namespace MMOserver.Game.Channel.Maps;
|
||||
|
||||
public class Robby
|
||||
{
|
||||
// 마을 시작 지점 넣어 둔다.
|
||||
public static Vector3 StartPosition
|
||||
{
|
||||
get;
|
||||
set;
|
||||
} = new Vector3(0, 0, 0);
|
||||
|
||||
public Robby()
|
||||
{
|
||||
}
|
||||
}
|
||||
36
MMOTestServer/MMOserver/Game/Engine/Vector3.cs
Normal file
36
MMOTestServer/MMOserver/Game/Engine/Vector3.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
namespace MMOserver.Game.Engine;
|
||||
|
||||
public class Vector3
|
||||
{
|
||||
public int X
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public int Y
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public int Z
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public Vector3()
|
||||
{
|
||||
X = 0;
|
||||
Y = 0;
|
||||
Z = 0;
|
||||
}
|
||||
|
||||
public Vector3(int x, int y, int z)
|
||||
{
|
||||
X = x;
|
||||
Y = y; // 수직 사실상 안쓰겠다.
|
||||
Z = z;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,303 @@
|
||||
using LiteNetLib;
|
||||
using LiteNetLib;
|
||||
using MMOserver.Game.Channel;
|
||||
using MMOserver.Packet;
|
||||
using ProtoBuf;
|
||||
using Serilog;
|
||||
using ServerLib.Packet;
|
||||
using ServerLib.Service;
|
||||
|
||||
namespace MMOserver.Game;
|
||||
|
||||
public class GameServer : ServerBase
|
||||
{
|
||||
private readonly Dictionary<ushort, Action<NetPeer, long, byte[]>> packetHandlers;
|
||||
|
||||
public GameServer(int port, string connectionString) : base(port, connectionString)
|
||||
{
|
||||
|
||||
packetHandlers = new Dictionary<ushort, Action<NetPeer, long, byte[]>>
|
||||
{
|
||||
[(ushort)PacketCode.INTO_CHANNEL] = OnIntoChannel,
|
||||
[(ushort)PacketCode.EXIT_CHANNEL] = OnExitChannel,
|
||||
[(ushort)PacketCode.TRANSFORM_PLAYER] = OnTransformPlayer,
|
||||
[(ushort)PacketCode.ACTION_PLAYER] = OnActionPlayer,
|
||||
[(ushort)PacketCode.STATE_PLAYER] = OnStatePlayer,
|
||||
};
|
||||
}
|
||||
|
||||
protected override void OnSessionConnected(NetPeer peer, long hashKey)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
Log.Information("[GameServer] 세션 연결 HashKey={Key} PeerId={Id}", hashKey, peer.Id);
|
||||
|
||||
// 만약 wifi-lte 로 바꿔졌다 이때 이미 로비에 들어가 있다면 넘긴다.
|
||||
ChannelManager cm = ChannelManager.Instance;
|
||||
int channelId = cm.HasUser(hashKey);
|
||||
|
||||
if (channelId >= 0)
|
||||
{
|
||||
// 재연결: 채널 유저 목록 전송 (채널 선택 스킵, 바로 마을로)
|
||||
SendIntoChannelPacket(peer, hashKey);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 모든 채널 정보 던진다
|
||||
SendLoadChannelPacket(peer, hashKey);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnSessionDisconnected(NetPeer peer, long hashKey, DisconnectInfo info)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
ChannelManager cm = ChannelManager.Instance;
|
||||
if (cm.RemoveUser(hashKey))
|
||||
{
|
||||
Log.Information("[GameServer] 세션 해제 HashKey={Key} Reason={Reason}", hashKey, info.Reason);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void HandlePacket(NetPeer peer, long hashKey, ushort type, byte[] payload)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
if (packetHandlers.TryGetValue(type, out Action<NetPeer, long, byte[]>? handler))
|
||||
{
|
||||
handler(peer, hashKey, payload);
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.Warning("[GameServer] 알 수 없는 패킷 Type={Type}", type);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 보내는 패킷
|
||||
// ============================================================
|
||||
|
||||
private void SendLoadChannelPacket(NetPeer peer, long hashKey)
|
||||
{
|
||||
LoadChannelPacket loadChannelPacket = new LoadChannelPacket();
|
||||
foreach (Channel.Channel channel in ChannelManager.Instance.GetChannels())
|
||||
{
|
||||
ChannelInfo info = new ChannelInfo();
|
||||
info.ChannelId = channel.ChannelId;
|
||||
info.ChannelUserConut = channel.UserCount;
|
||||
info.ChannelUserMax = channel.UserCountMax;
|
||||
loadChannelPacket.Channels.Add(info);
|
||||
}
|
||||
|
||||
byte[] data = PacketSerializer.Serialize<LoadChannelPacket>((ushort)PacketCode.LOAD_CHANNEL, loadChannelPacket);
|
||||
SendTo(peer, data);
|
||||
}
|
||||
|
||||
// 나간 유저를 같은 채널 유저들에게 알림 (UPDATE_CHANNEL_USER IsAdd=false)
|
||||
private void SendExitChannelPacket(NetPeer peer, long hashKey, int channelId, Player player)
|
||||
{
|
||||
UpdateChannelUserPacket packet = new UpdateChannelUserPacket
|
||||
{
|
||||
Players = ToPlayerInfo(player),
|
||||
IsAdd = false
|
||||
};
|
||||
byte[] data = PacketSerializer.Serialize<UpdateChannelUserPacket>((ushort)PacketCode.UPDATE_CHANNEL_USER, packet);
|
||||
// 이미 채널에서 제거된 후라 나간 본인에게는 전송되지 않음
|
||||
BroadcastToChannel(channelId, data);
|
||||
}
|
||||
|
||||
// 채널 입장 시 패킷 전송
|
||||
// - 새 유저에게 : 기존 채널 유저 목록 (INTO_CHANNEL)
|
||||
// - 기존 유저들에게 : 새 유저 입장 알림 (UPDATE_CHANNEL_USER IsAdd=true)
|
||||
private void SendIntoChannelPacket(NetPeer peer, long hashKey)
|
||||
{
|
||||
ChannelManager cm = ChannelManager.Instance;
|
||||
int channelId = cm.HasUser(hashKey);
|
||||
if (channelId < 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Channel.Channel channel = cm.GetChannel(channelId);
|
||||
Player? myPlayer = channel.GetPlayer(hashKey);
|
||||
|
||||
// 1. 새 유저에게: 자신을 제외한 기존 채널 유저 목록 전송
|
||||
IntoChannelPacket response = new IntoChannelPacket { ChannelId = channelId };
|
||||
foreach (long userId in channel.GetConnectUsers())
|
||||
{
|
||||
if (userId == hashKey)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
Player? p = channel.GetPlayer(userId);
|
||||
if (p != null)
|
||||
{
|
||||
response.Players.Add(ToPlayerInfo(p));
|
||||
}
|
||||
}
|
||||
|
||||
byte[] toNewUser = PacketSerializer.Serialize<IntoChannelPacket>((ushort)PacketCode.INTO_CHANNEL, response);
|
||||
SendTo(peer, toNewUser);
|
||||
|
||||
// 2. 기존 유저들에게: 새 유저 입장 알림
|
||||
if (myPlayer != null)
|
||||
{
|
||||
UpdateChannelUserPacket notify = new UpdateChannelUserPacket
|
||||
{
|
||||
Players = ToPlayerInfo(myPlayer),
|
||||
IsAdd = true
|
||||
};
|
||||
byte[] toOthers = PacketSerializer.Serialize<UpdateChannelUserPacket>((ushort)PacketCode.UPDATE_CHANNEL_USER, notify);
|
||||
BroadcastToChannel(channelId, toOthers, peer);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 채널 브로드캐스트 헬퍼
|
||||
// ============================================================
|
||||
|
||||
// 특정 채널의 모든 유저에게 전송 (exclude 지정 시 해당 피어 제외)
|
||||
private void BroadcastToChannel(int channelId, byte[] data, NetPeer? exclude = null)
|
||||
{
|
||||
Channel.Channel channel = ChannelManager.Instance.GetChannel(channelId);
|
||||
foreach (long userId in channel.GetConnectUsers())
|
||||
{
|
||||
if (!sessions.TryGetValue(userId, out NetPeer? targetPeer))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (exclude != null && targetPeer.Id == exclude.Id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
SendTo(targetPeer, data);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Player ↔ PlayerInfo 변환 (패킷 전송 시에만 사용)
|
||||
// ============================================================
|
||||
|
||||
private static PlayerInfo ToPlayerInfo(Player player)
|
||||
{
|
||||
return new PlayerInfo
|
||||
{
|
||||
PlayerId = player.PlayerId,
|
||||
Nickname = player.Nickname,
|
||||
Level = player.Level,
|
||||
Hp = player.Hp,
|
||||
MaxHp = player.MaxHp,
|
||||
Mp = player.Mp,
|
||||
MaxMp = player.MaxMp,
|
||||
Position = new Vector3 { X = player.PosX, Y = player.PosY, Z = player.PosZ },
|
||||
RotY = player.RotY,
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 패킷 핸들러
|
||||
// ============================================================
|
||||
|
||||
private void OnIntoChannel(NetPeer peer, long hashKey, byte[] payload)
|
||||
{
|
||||
IntoChannelPacket packet = Serializer.Deserialize<IntoChannelPacket>(new ReadOnlyMemory<byte>(payload));
|
||||
|
||||
ChannelManager cm = ChannelManager.Instance;
|
||||
|
||||
// TODO: 실제 서비스에서는 DB/세션에서 플레이어 정보 로드 필요
|
||||
Player newPlayer = new Player
|
||||
{
|
||||
HashKey = hashKey,
|
||||
PlayerId = (int)(hashKey & 0x7FFFFFFF),
|
||||
};
|
||||
|
||||
cm.AddUser(packet.ChannelId, hashKey, newPlayer);
|
||||
Log.Debug("[GameServer] INTO_CHANNEL HashKey={Key} ChannelId={ChannelId}", hashKey, packet.ChannelId);
|
||||
|
||||
// 접속된 모든 유저 정보 전달
|
||||
SendIntoChannelPacket(peer, hashKey);
|
||||
}
|
||||
|
||||
private void OnExitChannel(NetPeer peer, long hashKey, byte[] payload)
|
||||
{
|
||||
ExitChannelPacket packet = Serializer.Deserialize<ExitChannelPacket>(new ReadOnlyMemory<byte>(payload));
|
||||
|
||||
ChannelManager cm = ChannelManager.Instance;
|
||||
|
||||
// 제거 전에 채널/플레이어 정보 저장 (브로드캐스트에 필요)
|
||||
int channelId = cm.HasUser(hashKey);
|
||||
Player? player = channelId >= 0 ? cm.GetChannel(channelId).GetPlayer(hashKey) : null;
|
||||
|
||||
cm.RemoveUser(hashKey);
|
||||
Log.Debug("[GameServer] EXIT_CHANNEL HashKey={Key} PlayerId={PlayerId}", hashKey, packet.PlayerId);
|
||||
|
||||
// 같은 채널 유저들에게 나갔다고 알림
|
||||
if (channelId >= 0 && player != null)
|
||||
{
|
||||
SendExitChannelPacket(peer, hashKey, channelId, player);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnTransformPlayer(NetPeer peer, long hashKey, byte[] payload)
|
||||
{
|
||||
TransformPlayerPacket packet = Serializer.Deserialize<TransformPlayerPacket>(new ReadOnlyMemory<byte>(payload));
|
||||
|
||||
ChannelManager cm = ChannelManager.Instance;
|
||||
int channelId = cm.HasUser(hashKey);
|
||||
if (channelId < 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 채널 내 플레이어 위치/방향 상태 갱신
|
||||
Player? player = cm.GetChannel(channelId).GetPlayer(hashKey);
|
||||
if (player != null)
|
||||
{
|
||||
player.PosX = packet.Position.X;
|
||||
player.PosY = packet.Position.Y;
|
||||
player.PosZ = packet.Position.Z;
|
||||
player.RotY = packet.RotY;
|
||||
}
|
||||
|
||||
// 같은 채널 유저들에게 위치/방향 브로드캐스트 (나 제외)
|
||||
byte[] data = PacketSerializer.Serialize<TransformPlayerPacket>((ushort)PacketCode.TRANSFORM_PLAYER, packet);
|
||||
BroadcastToChannel(channelId, data, peer);
|
||||
}
|
||||
|
||||
private void OnActionPlayer(NetPeer peer, long hashKey, byte[] payload)
|
||||
{
|
||||
ActionPlayerPacket packet = Serializer.Deserialize<ActionPlayerPacket>(new ReadOnlyMemory<byte>(payload));
|
||||
|
||||
ChannelManager cm = ChannelManager.Instance;
|
||||
int channelId = cm.HasUser(hashKey);
|
||||
if (channelId < 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 같은 채널 유저들에게 행동 브로드캐스트 (나 제외)
|
||||
byte[] data = PacketSerializer.Serialize<ActionPlayerPacket>((ushort)PacketCode.ACTION_PLAYER, packet);
|
||||
BroadcastToChannel(channelId, data, peer);
|
||||
}
|
||||
|
||||
private void OnStatePlayer(NetPeer peer, long hashKey, byte[] payload)
|
||||
{
|
||||
StatePlayerPacket packet = Serializer.Deserialize<StatePlayerPacket>(new ReadOnlyMemory<byte>(payload));
|
||||
|
||||
ChannelManager cm = ChannelManager.Instance;
|
||||
int channelId = cm.HasUser(hashKey);
|
||||
if (channelId < 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 채널 내 플레이어 HP/MP 상태 갱신
|
||||
Player? player = cm.GetChannel(channelId).GetPlayer(hashKey);
|
||||
if (player != null)
|
||||
{
|
||||
player.Hp = packet.Hp;
|
||||
player.MaxHp = packet.MaxHp;
|
||||
player.Mp = packet.Mp;
|
||||
player.MaxMp = packet.MaxMp;
|
||||
}
|
||||
|
||||
// 같은 채널 유저들에게 스테이트 브로드캐스트 (나 제외)
|
||||
byte[] data = PacketSerializer.Serialize<StatePlayerPacket>((ushort)PacketCode.STATE_PLAYER, packet);
|
||||
BroadcastToChannel(channelId, data, peer);
|
||||
}
|
||||
}
|
||||
|
||||
77
MMOTestServer/MMOserver/Game/Player.cs
Normal file
77
MMOTestServer/MMOserver/Game/Player.cs
Normal file
@@ -0,0 +1,77 @@
|
||||
namespace MMOserver.Game;
|
||||
|
||||
public class Player
|
||||
{
|
||||
public long HashKey
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public int PlayerId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public string Nickname
|
||||
{
|
||||
get;
|
||||
set;
|
||||
} = string.Empty;
|
||||
|
||||
public int Level
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public int Hp
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public int MaxHp
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public int Mp
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public int MaxMp
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
// 위치/방향 (클라이언트 패킷과 동일하게 float)
|
||||
public float PosX
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public float PosY
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public float PosZ
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public float RotY
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
@@ -100,24 +100,6 @@ public class PlayerInfo
|
||||
}
|
||||
}
|
||||
|
||||
[ProtoContract]
|
||||
public class ItemInfo
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public int ItemId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(2)]
|
||||
public int Count
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 인증
|
||||
// ============================================================
|
||||
@@ -134,7 +116,7 @@ public class RecvTokenPacket
|
||||
}
|
||||
}
|
||||
|
||||
// LOAD_GAME
|
||||
// LOAD_GAME 내 정보
|
||||
[ProtoContract]
|
||||
public class LoadGamePacket
|
||||
{
|
||||
@@ -151,27 +133,96 @@ public class LoadGamePacket
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(3)]
|
||||
public int MaplId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 로비
|
||||
// ============================================================
|
||||
|
||||
// INTO_LOBBY
|
||||
[ProtoContract]
|
||||
public class IntoLobbyPacket
|
||||
public class ChannelInfo
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public int ChannelId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(2)]
|
||||
public int ChannelUserConut
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(3)]
|
||||
public int ChannelUserMax
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
[ProtoContract]
|
||||
public class LoadChannelPacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public List<ChannelInfo> Channels
|
||||
{
|
||||
get;
|
||||
set;
|
||||
} = new List<ChannelInfo>();
|
||||
}
|
||||
|
||||
// INTO_CHANNEL 클라->서버: 입장할 채널 ID / 서버->클라: 채널 내 나 이외 플레이어 목록
|
||||
[ProtoContract]
|
||||
public class IntoChannelPacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public int ChannelId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
} // 클라->서버: 입장할 채널 ID
|
||||
|
||||
[ProtoMember(2)]
|
||||
public List<PlayerInfo> Players
|
||||
{
|
||||
get;
|
||||
set;
|
||||
} = new List<PlayerInfo>(); // 서버->클라: 채널 내 플레이어 목록
|
||||
}
|
||||
|
||||
// UPDATE_CHANNEL_USER 유저 접속/나감
|
||||
[ProtoContract]
|
||||
public class UpdateChannelUserPacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public PlayerInfo Players
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(2)]
|
||||
public bool IsAdd
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
// EXIT_LOBBY
|
||||
// EXIT_CHANNEL 나가는 유저
|
||||
[ProtoContract]
|
||||
public class ExitLobbyPacket
|
||||
public class ExitChannelPacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public int PlayerId
|
||||
@@ -181,174 +232,6 @@ public class ExitLobbyPacket
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 인스턴스 던전
|
||||
// ============================================================
|
||||
|
||||
public enum BossState
|
||||
{
|
||||
START,
|
||||
END,
|
||||
PHASE_CHANGE
|
||||
}
|
||||
|
||||
public enum BossResult
|
||||
{
|
||||
SUCCESS,
|
||||
FAIL
|
||||
}
|
||||
|
||||
// INTO_INSTANCE
|
||||
[ProtoContract]
|
||||
public class IntoInstancePacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public int InstanceId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(2)]
|
||||
public int BossId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(3)]
|
||||
public List<int> PlayerIds
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
// UPDATE_BOSS
|
||||
[ProtoContract]
|
||||
public class UpdateBossPacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public BossState State
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(2)]
|
||||
public int Phase
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(3)]
|
||||
public BossResult Result
|
||||
{
|
||||
get;
|
||||
set;
|
||||
} // END일 때만 유효
|
||||
}
|
||||
|
||||
// REWARD_INSTANCE
|
||||
[ProtoContract]
|
||||
public class RewardInstancePacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public int Exp
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(2)]
|
||||
public List<ItemInfo> Items
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
// EXIT_INSTANCE
|
||||
[ProtoContract]
|
||||
public class ExitInstancePacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public int PlayerId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 파티
|
||||
// ============================================================
|
||||
|
||||
public enum PartyUpdateType
|
||||
{
|
||||
CREATE,
|
||||
DELETE
|
||||
}
|
||||
|
||||
public enum UserPartyUpdateType
|
||||
{
|
||||
JOIN,
|
||||
LEAVE
|
||||
}
|
||||
|
||||
// UPDATE_PARTY
|
||||
[ProtoContract]
|
||||
public class UpdatePartyPacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public int PartyId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(2)]
|
||||
public PartyUpdateType Type
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(3)]
|
||||
public int LeaderId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
// UPDATE_USER_PARTY
|
||||
[ProtoContract]
|
||||
public class UpdateUserPartyPacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public int PartyId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(2)]
|
||||
public int PlayerId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(3)]
|
||||
public UserPartyUpdateType Type
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 플레이어
|
||||
// ============================================================
|
||||
@@ -604,3 +487,71 @@ public class DamagePacket
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 파티
|
||||
// ============================================================
|
||||
|
||||
public enum PartyUpdateType
|
||||
{
|
||||
CREATE,
|
||||
DELETE
|
||||
}
|
||||
|
||||
public enum UserPartyUpdateType
|
||||
{
|
||||
JOIN,
|
||||
LEAVE
|
||||
}
|
||||
|
||||
// UPDATE_PARTY
|
||||
[ProtoContract]
|
||||
public class UpdatePartyPacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public int PartyId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(2)]
|
||||
public PartyUpdateType Type
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(3)]
|
||||
public int LeaderId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
// UPDATE_USER_PARTY
|
||||
[ProtoContract]
|
||||
public class UpdateUserPartyPacket
|
||||
{
|
||||
[ProtoMember(1)]
|
||||
public int PartyId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(2)]
|
||||
public int PlayerId
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
[ProtoMember(3)]
|
||||
public UserPartyUpdateType Type
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,61 +1,56 @@
|
||||
namespace MMOserver.Packet;
|
||||
|
||||
public enum PacketCode : short
|
||||
public enum PacketCode : ushort
|
||||
{
|
||||
NONE,
|
||||
// 초기 클라이언트 시작시 jwt토큰 받아옴
|
||||
RECV_TOKEN,
|
||||
// jwt토큰 검증후 게임에 들어갈지 말지 (내 데이터도 전송)
|
||||
|
||||
// 내 정보 로드 (서버 -> 클라)
|
||||
LOAD_GAME,
|
||||
|
||||
// 마을(로비)진입시 모든 데이터 로드
|
||||
INTO_LOBBY,
|
||||
// 모든 채널 로드 - jwt토큰 검증후 게임에 들어갈지 말지 (내 데이터도 전송)
|
||||
// (서버 -> 클라)
|
||||
LOAD_CHANNEL,
|
||||
|
||||
// 로비 나가기
|
||||
EXIT_LOBBY,
|
||||
// 나 채널 접속 (클라 -> 서버)
|
||||
INTO_CHANNEL,
|
||||
|
||||
// 인스턴스 던전 입장
|
||||
INTO_INSTANCE,
|
||||
// 새로운 유저 채널 접속 (서버 -> 클라) / 유저 채널 나감 (서버 -> 클라)
|
||||
UPDATE_CHANNEL_USER,
|
||||
|
||||
// 결과 보상
|
||||
REWARD_INSTANCE,
|
||||
// 채널 나가기 (클라 -> 서버)
|
||||
EXIT_CHANNEL,
|
||||
|
||||
// 보스전 (시작, 종료)
|
||||
UPDATE_BOSS,
|
||||
// 플레이어 위치, 방향 (서버 -> 클라 \ 클라 -> 서버)
|
||||
TRANSFORM_PLAYER,
|
||||
|
||||
// 인스턴스 던전 퇴장
|
||||
EXIT_INSTANCE,
|
||||
// 플레이어 행동 업데이트 (서버 -> 클라 \ 클라 -> 서버)
|
||||
ACTION_PLAYER,
|
||||
|
||||
// 플레이어 스테이트 업데이트 (서버 -> 클라 \ 클라 -> 서버)
|
||||
STATE_PLAYER,
|
||||
|
||||
// NPC 위치, 방향 (서버 -> 클라)
|
||||
TRANSFORM_NPC,
|
||||
|
||||
// NPC 행동 업데이트 (서버 -> 클라)
|
||||
ACTION_NPC,
|
||||
|
||||
// NPC 스테이트 업데이트 (서버 -> 클라)
|
||||
STATE_NPC,
|
||||
|
||||
// 데미지 UI 전달 (서버 -> 클라)
|
||||
DAMAGE,
|
||||
|
||||
// 파티 (생성, 삭제)
|
||||
UPDATE_PARTY,
|
||||
|
||||
// 파티 유저 업데이트(추가 삭제)
|
||||
UPDATE_USER_PARTY,
|
||||
|
||||
// 플레이어 위치, 방향
|
||||
TRANSFORM_PLAYER,
|
||||
|
||||
// 플레이어 행동 업데이트
|
||||
ACTION_PLAYER,
|
||||
|
||||
// 플레이어 스테이트 업데이트
|
||||
STATE_PLAYER,
|
||||
|
||||
// NPC 위치, 방향
|
||||
TRANSFORM_NPC,
|
||||
|
||||
// NPC 행동 업데이트
|
||||
ACTION_NPC,
|
||||
|
||||
// NPC 스테이트 업데이트
|
||||
STATE_NPC,
|
||||
|
||||
// 데미지 UI 전달
|
||||
DAMAGE
|
||||
UPDATE_USER_PARTY
|
||||
}
|
||||
|
||||
public class PacketHeader
|
||||
{
|
||||
public PacketCode Code;
|
||||
public int BodyLength;
|
||||
public ushort BodyLength;
|
||||
}
|
||||
|
||||
@@ -11,38 +11,80 @@ public class TestHandler
|
||||
public TestHandler(TestService testService) => _testService = testService;
|
||||
|
||||
public async Task<string> GetTestAsync(int id)
|
||||
{
|
||||
try
|
||||
{
|
||||
Test? result = await _testService.GetTestAsync(id);
|
||||
return result is null
|
||||
? HandlerHelper.Error("Test not found")
|
||||
: HandlerHelper.Success(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return HandlerHelper.Error(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> GetTestByUuidAsync(string uuid)
|
||||
{
|
||||
try
|
||||
{
|
||||
Test? result = await _testService.GetTestByUuidAsync(uuid);
|
||||
return result is null
|
||||
? HandlerHelper.Error("Test not found")
|
||||
: HandlerHelper.Success(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return HandlerHelper.Error(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> GetAllTestsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
return HandlerHelper.Success(await _testService.GetAllTestsAsync());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return HandlerHelper.Error(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> CreateTestAsync(int testA, string testB, double testC)
|
||||
{
|
||||
try
|
||||
{
|
||||
return HandlerHelper.Success(await _testService.CreateTestAsync(testA, testB, testC));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return HandlerHelper.Error(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> UpdateTestAsync(int id, int? testA, string? testB, double? testC)
|
||||
{
|
||||
try
|
||||
{
|
||||
return HandlerHelper.Success(await _testService.UpdateTestAsync(id, testA, testB, testC));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return HandlerHelper.Error(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> DeleteTestAsync(int id)
|
||||
{
|
||||
try
|
||||
{
|
||||
return HandlerHelper.Success(await _testService.DeleteTestAsync(id));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return HandlerHelper.Error(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace MMOserver.RDB.Repositories;
|
||||
// 실제 호출할 쿼리들
|
||||
public class TestRepository : ARepository<Test>
|
||||
{
|
||||
public TestRepository(DbConnectionFactory factory) : base(factory)
|
||||
public TestRepository(IDbConnectionFactory factory) : base(factory)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
@@ -9,22 +9,24 @@ namespace ServerLib.Packet
|
||||
|
||||
public static class PacketSerializer
|
||||
{
|
||||
// 직렬화: 객체 → byte[]
|
||||
public static byte[] Serialize<T>(ushort type, ushort size, T packet)
|
||||
// 직렬화: 객체 → byte[] (size는 payload 크기로 자동 계산)
|
||||
public static byte[] Serialize<T>(ushort type, T packet)
|
||||
{
|
||||
MemoryStream ms = new MemoryStream();
|
||||
using MemoryStream payloadMs = new MemoryStream();
|
||||
Serializer.Serialize(payloadMs, packet);
|
||||
byte[] payload = payloadMs.ToArray();
|
||||
ushort size = (ushort)payload.Length;
|
||||
|
||||
byte[] result = new byte[4 + payload.Length];
|
||||
// 2바이트 패킷 타입 헤더
|
||||
ms.WriteByte((byte)(type & 0xFF));
|
||||
ms.WriteByte((byte)(type >> 8));
|
||||
|
||||
result[0] = (byte)(type & 0xFF);
|
||||
result[1] = (byte)(type >> 8);
|
||||
// 2바이트 패킷 길이 헤더
|
||||
ms.WriteByte((byte)(size & 0xFF));
|
||||
ms.WriteByte((byte)(size >> 8));
|
||||
|
||||
result[2] = (byte)(size & 0xFF);
|
||||
result[3] = (byte)(size >> 8);
|
||||
// protobuf 페이로드
|
||||
Serializer.Serialize(ms, packet);
|
||||
return ms.ToArray();
|
||||
Buffer.BlockCopy(payload, 0, result, 4, payload.Length);
|
||||
return result;
|
||||
}
|
||||
|
||||
// 역직렬화: byte[] → (PacketType, payload bytes)
|
||||
@@ -36,19 +38,26 @@ namespace ServerLib.Packet
|
||||
return (0, 0, null)!;
|
||||
}
|
||||
|
||||
// 길이체크도 필요함
|
||||
|
||||
ushort type = (ushort)(data[0] | (data[1] << 8));
|
||||
ushort size = (ushort)(data[2] | (data[3] << 8));
|
||||
byte[] payload = new byte[data.Length - 4];
|
||||
Buffer.BlockCopy(data, 4, payload, 0, payload.Length);
|
||||
|
||||
// 헤더에 명시된 size와 실제 데이터 길이 검증
|
||||
int actualPayloadLen = data.Length - 4;
|
||||
if (size > actualPayloadLen)
|
||||
{
|
||||
Log.Warning("[PacketSerializer] 페이로드 크기 불일치 HeaderSize={Size} ActualSize={Actual}", size, actualPayloadLen);
|
||||
return (0, 0, null)!;
|
||||
}
|
||||
|
||||
byte[] payload = new byte[size];
|
||||
Buffer.BlockCopy(data, 4, payload, 0, size);
|
||||
return (type, size, payload);
|
||||
}
|
||||
|
||||
// 페이로드 → 특정 타입으로 역직렬화
|
||||
public static T DeserializePayload<T>(byte[] payload)
|
||||
{
|
||||
MemoryStream ms = new MemoryStream(payload);
|
||||
using MemoryStream ms = new MemoryStream(payload);
|
||||
return Serializer.Deserialize<T>(ms);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,59 +22,59 @@ public abstract class ARepository<T> where T : class
|
||||
// Dapper.Contrib 기본 CRUD
|
||||
public async Task<T?> GetByIdAsync(int id)
|
||||
{
|
||||
IDbConnection conn = CreateConnection();
|
||||
using IDbConnection conn = CreateConnection();
|
||||
return await conn.GetAsync<T>(id);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<T>> GetAllAsync()
|
||||
{
|
||||
IDbConnection conn = CreateConnection();
|
||||
using IDbConnection conn = CreateConnection();
|
||||
return await conn.GetAllAsync<T>();
|
||||
}
|
||||
|
||||
public async Task<long> InsertAsync(T entity)
|
||||
{
|
||||
IDbConnection conn = CreateConnection();
|
||||
using IDbConnection conn = CreateConnection();
|
||||
return await conn.InsertAsync(entity);
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(T entity)
|
||||
{
|
||||
IDbConnection conn = CreateConnection();
|
||||
using IDbConnection conn = CreateConnection();
|
||||
return await conn.UpdateAsync(entity);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(T entity)
|
||||
{
|
||||
IDbConnection conn = CreateConnection();
|
||||
using IDbConnection conn = CreateConnection();
|
||||
return await conn.DeleteAsync(entity);
|
||||
}
|
||||
|
||||
// 커스텀 쿼리 헬퍼 (복잡한 쿼리용)
|
||||
protected async Task<IEnumerable<T>> QueryAsync(string sql, object? param = null)
|
||||
{
|
||||
IDbConnection conn = CreateConnection();
|
||||
using IDbConnection conn = CreateConnection();
|
||||
return await conn.QueryAsync<T>(sql, param);
|
||||
}
|
||||
|
||||
protected async Task<T?> QueryFirstOrDefaultAsync(string sql, object? param = null)
|
||||
{
|
||||
IDbConnection conn = CreateConnection();
|
||||
using IDbConnection conn = CreateConnection();
|
||||
return await conn.QueryFirstOrDefaultAsync<T>(sql, param);
|
||||
}
|
||||
|
||||
protected async Task<int> ExecuteAsync(string sql, object? param = null)
|
||||
{
|
||||
IDbConnection conn = CreateConnection();
|
||||
using IDbConnection conn = CreateConnection();
|
||||
return await conn.ExecuteAsync(sql, param);
|
||||
}
|
||||
|
||||
// 트랜잭션 헬퍼
|
||||
protected async Task<TResult> WithTransactionAsync<TResult>(Func<IDbConnection, IDbTransaction, Task<TResult>> action)
|
||||
{
|
||||
IDbConnection conn = CreateConnection();
|
||||
using IDbConnection conn = CreateConnection();
|
||||
conn.Open();
|
||||
IDbTransaction tx = conn.BeginTransaction();
|
||||
using IDbTransaction tx = conn.BeginTransaction();
|
||||
try
|
||||
{
|
||||
TResult result = await action(conn, tx);
|
||||
|
||||
@@ -34,15 +34,29 @@ public abstract class ServerBase : INetEventListener
|
||||
|
||||
// 인증된 세션 (hashKey → NetPeer) 재연결 조회용
|
||||
// peer → hashKey 역방향은 peer.Tag as Session 으로 대체
|
||||
private readonly Dictionary<long, NetPeer> sessions = new();
|
||||
protected readonly Dictionary<long, NetPeer> sessions = new();
|
||||
|
||||
// 재사용 NetDataWriter (단일 스레드 폴링이므로 안전)
|
||||
private readonly NetDataWriter cachedWriter = new();
|
||||
|
||||
// 핑 로그 출력 여부
|
||||
public bool PingLogRtt { get; set; }
|
||||
public bool PingLogRtt
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
|
||||
public int Port { get; }
|
||||
public string ConnectionString { get; }
|
||||
public int Port
|
||||
{
|
||||
get;
|
||||
}
|
||||
|
||||
private bool isListening = false;
|
||||
public string ConnectionString
|
||||
{
|
||||
get;
|
||||
}
|
||||
|
||||
private volatile bool isListening = false;
|
||||
|
||||
public ServerBase(int port, string connectionString)
|
||||
{
|
||||
@@ -71,6 +85,7 @@ public abstract class ServerBase : INetEventListener
|
||||
netManager.PollEvents();
|
||||
await Task.Delay(1);
|
||||
}
|
||||
|
||||
netManager.Stop();
|
||||
Log.Information("[Server] 종료 Port={Port}", Port);
|
||||
}
|
||||
@@ -86,7 +101,7 @@ public abstract class ServerBase : INetEventListener
|
||||
// 벤 기능 추가? 한국 ip만?
|
||||
if (request.AcceptIfKey(ConnectionString) == null)
|
||||
{
|
||||
Log.Debug("해당 클라이언트의 ConnectionKey={request.ConnectionKey}가 동일하지 않습니다", request.Data.ToString());
|
||||
Log.Debug("해당 클라이언트의 ConnectionKey가 동일하지 않습니다. Data={Data}", request.Data.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +127,7 @@ public abstract class ServerBase : INetEventListener
|
||||
Log.Information("[Server] 세션 해제 HashKey={Key} Reason={Reason}", session.HashKey, disconnectInfo.Reason);
|
||||
OnSessionDisconnected(peer, session.HashKey, disconnectInfo);
|
||||
}
|
||||
|
||||
peer.Tag = null;
|
||||
}
|
||||
}
|
||||
@@ -125,6 +141,13 @@ public abstract class ServerBase : INetEventListener
|
||||
{
|
||||
(ushort type, ushort size, byte[] payload) = PacketSerializer.Deserialize(data);
|
||||
|
||||
// Deserialize 실패 시 payload가 null
|
||||
if (payload == null)
|
||||
{
|
||||
Log.Warning("[Server] 패킷 역직렬화 실패 PeerId={Id} DataLen={Len}", peer.Id, data.Length);
|
||||
return;
|
||||
}
|
||||
|
||||
// 0이라면 에코 서버 테스트용 따로 처리
|
||||
if (type == 0)
|
||||
{
|
||||
@@ -181,12 +204,11 @@ public abstract class ServerBase : INetEventListener
|
||||
|
||||
private void HandleEcho(NetPeer peer, byte[] payload)
|
||||
{
|
||||
// if (payload.Length < sizeof(long))
|
||||
// {
|
||||
// Log.Warning("[Server] Echo 페이로드 크기 오류 PeerId={Id}", peer.Id);
|
||||
// peer.Disconnect();
|
||||
// return;
|
||||
// }
|
||||
if (payload.Length < 4)
|
||||
{
|
||||
Log.Warning("[Server] Echo 페이로드 크기 오류 PeerId={Id} Length={Len}", peer.Id, payload.Length);
|
||||
return;
|
||||
}
|
||||
|
||||
// 세션에 넣지는 않는다.
|
||||
NetDataReader reader = new NetDataReader(payload);
|
||||
@@ -201,12 +223,12 @@ public abstract class ServerBase : INetEventListener
|
||||
|
||||
private void HandleAuth(NetPeer peer, byte[] payload)
|
||||
{
|
||||
// if (payload.Length < sizeof(long))
|
||||
// {
|
||||
// Log.Warning("[Server] Auth 페이로드 크기 오류 PeerId={Id}", peer.Id);
|
||||
// peer.Disconnect();
|
||||
// return;
|
||||
// }
|
||||
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);
|
||||
|
||||
@@ -229,31 +251,28 @@ public abstract class ServerBase : INetEventListener
|
||||
|
||||
// ─── 전송 헬퍼 ───────────────────────────────────────────────────────
|
||||
|
||||
// NetDataWriter writer 풀처리 필요할듯
|
||||
// peer에게 전송
|
||||
protected void SendTo(NetPeer peer, byte[] data, DeliveryMethod method = DeliveryMethod.ReliableOrdered)
|
||||
{
|
||||
NetDataWriter writer = new NetDataWriter();
|
||||
writer.Put(data);
|
||||
peer.Send(writer, method);
|
||||
cachedWriter.Reset();
|
||||
cachedWriter.Put(data);
|
||||
peer.Send(cachedWriter, method);
|
||||
}
|
||||
|
||||
// 모두에게 전송
|
||||
protected void Broadcast(byte[] data, DeliveryMethod method = DeliveryMethod.ReliableOrdered)
|
||||
{
|
||||
// 일단 channelNumber는 건드리지 않는다
|
||||
NetDataWriter writer = new NetDataWriter();
|
||||
writer.Put(data);
|
||||
netManager.SendToAll(writer, 0, method);
|
||||
cachedWriter.Reset();
|
||||
cachedWriter.Put(data);
|
||||
netManager.SendToAll(cachedWriter, 0, method);
|
||||
}
|
||||
|
||||
// exclude 1개 제외 / 나 제외 정도
|
||||
protected void BroadcastExcept(byte[] data, NetPeer exclude, DeliveryMethod method = DeliveryMethod.ReliableOrdered)
|
||||
{
|
||||
// 일단 channelNumber는 건드리지 않는다
|
||||
NetDataWriter writer = new NetDataWriter();
|
||||
writer.Put(data);
|
||||
netManager.SendToAll(writer, 0, method, exclude);
|
||||
cachedWriter.Reset();
|
||||
cachedWriter.Put(data);
|
||||
netManager.SendToAll(cachedWriter, 0, method, exclude);
|
||||
}
|
||||
|
||||
// ─── 서브클래스 구현 ─────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user