mirror of
https://github.com/Sanae6/SmoOnlineServer.git
synced 2024-11-24 20:25:18 +00:00
Server overhaul, might rewrite though
This commit is contained in:
parent
cdad20ddd2
commit
de16e4a787
16 changed files with 469 additions and 359 deletions
332
Server/Server.cs
332
Server/Server.cs
|
@ -1,164 +1,170 @@
|
|||
using System.Buffers;
|
||||
using System.Net.Sockets;
|
||||
using System.Runtime.InteropServices;
|
||||
using Shared;
|
||||
using Shared.Packet;
|
||||
using Shared.Packet.Packets;
|
||||
|
||||
namespace Server;
|
||||
|
||||
public class Server {
|
||||
private readonly MemoryPool<byte> memoryPool = MemoryPool<byte>.Shared;
|
||||
public readonly List<Client> Clients = new List<Client>();
|
||||
public readonly Logger Logger = new Logger("Server");
|
||||
public async Task Listen(ushort port) {
|
||||
TcpListener listener = TcpListener.Create(port);
|
||||
|
||||
listener.Start();
|
||||
|
||||
while (true) {
|
||||
Socket socket = await listener.AcceptSocketAsync();
|
||||
|
||||
if (Clients.Count > Constants.MaxClients) {
|
||||
Logger.Warn("Turned away client due to max clients");
|
||||
await socket.DisconnectAsync(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
HandleSocket(socket);
|
||||
}
|
||||
}
|
||||
|
||||
public static void FillPacket<T>(PacketHeader header, T packet, Memory<byte> memory) where T : unmanaged, IPacket {
|
||||
Span<byte> data = memory.Span;
|
||||
|
||||
MemoryMarshal.Write(data, ref header);
|
||||
MemoryMarshal.Write(data[Constants.HeaderSize..], ref packet);
|
||||
}
|
||||
|
||||
// broadcast packets to all clients
|
||||
public async void Broadcast<T>(T packet, Client? sender = null) where T : unmanaged, IPacket {
|
||||
IMemoryOwner<byte> memory = memoryPool.Rent(Marshal.SizeOf<T>() + Constants.HeaderSize);
|
||||
|
||||
PacketHeader header = new PacketHeader {
|
||||
Id = sender?.Id ?? Guid.Empty,
|
||||
Type = Constants.Packets[typeof(T)].Type,
|
||||
Sender = PacketSender.Server // todo maybe use client?
|
||||
};
|
||||
FillPacket(header, packet, memory.Memory);
|
||||
await Broadcast(memory, sender);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes ownership of data and disposes once done.
|
||||
/// </summary>
|
||||
/// <param name="data">Memory owner to dispose once done</param>
|
||||
/// <param name="sender">Optional sender to not broadcast data to</param>
|
||||
public async Task Broadcast(IMemoryOwner<byte> data, Client? sender = null) {
|
||||
await Task.WhenAll(Clients.Where(c => c.Connected && c != sender).Select(client => client.Send(data.Memory)));
|
||||
data.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcasts memory whose memory shouldn't be disposed, should only be fired by server code.
|
||||
/// </summary>
|
||||
/// <param name="data">Memory to send to the clients</param>
|
||||
/// <param name="sender">Optional sender to not broadcast data to</param>
|
||||
public async void Broadcast(Memory<byte> data, Client? sender = null) {
|
||||
await Task.WhenAll(Clients.Where(c => c.Connected && c != sender).Select(client => client.Send(data)));
|
||||
}
|
||||
|
||||
public Client? FindExistingClient(Guid id) {
|
||||
return Clients.Find(client => client.Id == id);
|
||||
}
|
||||
|
||||
|
||||
private async void HandleSocket(Socket socket) {
|
||||
Client client = new Client {Socket = socket};
|
||||
IMemoryOwner<byte> memory = null!;
|
||||
bool first = true;
|
||||
try {
|
||||
while (true) {
|
||||
memory = memoryPool.Rent(Constants.MaxPacketSize);
|
||||
int size = await socket.ReceiveAsync(memory.Memory, SocketFlags.None);
|
||||
if (size == 0) { // treat it as a disconnect and exit
|
||||
Logger.Info($"Socket {socket.RemoteEndPoint} disconnected.");
|
||||
await socket.DisconnectAsync(false);
|
||||
break;
|
||||
}
|
||||
|
||||
PacketHeader header = GetHeader(memory.Memory.Span[..size]);
|
||||
//Logger.Info($"first = {first}, type = {header.Type}, data = " + memory.Memory.Span[..size].Hex());
|
||||
// connection initialization
|
||||
if (first) {
|
||||
first = false;
|
||||
if (header.Type != PacketType.Connect) {
|
||||
throw new Exception($"First packet was not init, instead it was {header.Type}");
|
||||
}
|
||||
|
||||
ConnectPacket connect = MemoryMarshal.Read<ConnectPacket>(memory.Memory.Span[Constants.HeaderSize..size]);
|
||||
lock (Clients) {
|
||||
switch (connect.ConnectionType) {
|
||||
case ConnectionTypes.FirstConnection: {
|
||||
// do any cleanup required when it comes to new clients
|
||||
List<Client> toDisconnect = Clients.FindAll(c => c.Id == header.Id && c.Connected && c.Socket != null);
|
||||
Clients.RemoveAll(c => c.Id == header.Id);
|
||||
|
||||
client.Id = header.Id;
|
||||
Clients.Add(client);
|
||||
|
||||
foreach (Client c in toDisconnect) c.Socket!.DisconnectAsync(false);
|
||||
// done disconnecting and removing stale clients with the same id
|
||||
break;
|
||||
}
|
||||
case ConnectionTypes.Reconnecting: {
|
||||
if (FindExistingClient(header.Id) is { } newClient) {
|
||||
if (newClient.Connected) throw new Exception($"Tried to join as already connected user {header.Id}");
|
||||
newClient.Socket = client.Socket;
|
||||
client = newClient;
|
||||
} else {
|
||||
// TODO MAJOR: IF CLIENT COULD NOT BE FOUND, SERVER SHOULD GRACEFULLY TELL CLIENT THAT ON DISCONNECT
|
||||
// can be done via disconnect packet when that gets more data?
|
||||
throw new Exception("Could not find a suitable client to reconnect as");
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Exception($"Invalid connection type {connect.ConnectionType}");
|
||||
}
|
||||
}
|
||||
|
||||
Logger.Info($"Client {socket.RemoteEndPoint} connected.");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
// todo support variable length packets when they show up
|
||||
if (header.Sender == PacketSender.Client) {
|
||||
Logger.Warn($"broadcasting {header.Type}");
|
||||
await Broadcast(memory, client);
|
||||
}
|
||||
else {
|
||||
//todo handle server packets :)
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
if (e is SocketException {SocketErrorCode: SocketError.ConnectionReset}) {
|
||||
Logger.Info($"Client {socket.RemoteEndPoint} disconnected from the server");
|
||||
} else {
|
||||
Logger.Error($"Exception on socket {socket.RemoteEndPoint}, disconnecting for: {e}");
|
||||
await socket.DisconnectAsync(false);
|
||||
}
|
||||
|
||||
memory?.Dispose();
|
||||
}
|
||||
client.Dispose();
|
||||
}
|
||||
|
||||
private static PacketHeader GetHeader(Span<byte> data) {
|
||||
//no need to error check, the client will disconnect when the packet is invalid :)
|
||||
return MemoryMarshal.Read<PacketHeader>(data);
|
||||
}
|
||||
using System.Buffers;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Runtime.InteropServices;
|
||||
using Shared;
|
||||
using Shared.Packet;
|
||||
using Shared.Packet.Packets;
|
||||
|
||||
namespace Server;
|
||||
|
||||
public class Server {
|
||||
private readonly MemoryPool<byte> memoryPool = MemoryPool<byte>.Shared;
|
||||
public readonly List<Client> Clients = new List<Client>();
|
||||
public readonly Logger Logger = new Logger("Server");
|
||||
public async Task Listen(ushort port) {
|
||||
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
serverSocket.Bind(new IPEndPoint(IPAddress.Loopback, port));
|
||||
serverSocket.Listen();
|
||||
|
||||
Logger.Info($"Listening on port {port}");
|
||||
|
||||
while (true) {
|
||||
Socket socket = await serverSocket.AcceptAsync();
|
||||
|
||||
Logger.Warn("ok");
|
||||
|
||||
if (Clients.Count > Constants.MaxClients) {
|
||||
Logger.Warn("Turned away client due to max clients");
|
||||
await socket.DisconnectAsync(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
HandleSocket(socket);
|
||||
}
|
||||
}
|
||||
|
||||
public static void FillPacket<T>(PacketHeader header, T packet, Memory<byte> memory) where T : unmanaged, IPacket {
|
||||
Span<byte> data = memory.Span;
|
||||
|
||||
MemoryMarshal.Write(data, ref header);
|
||||
MemoryMarshal.Write(data[Constants.HeaderSize..], ref packet);
|
||||
}
|
||||
|
||||
// broadcast packets to all clients
|
||||
public async Task Broadcast<T>(T packet, Client? sender = null) where T : unmanaged, IPacket {
|
||||
IMemoryOwner<byte> memory = memoryPool.Rent(Marshal.SizeOf<T>() + Constants.HeaderSize);
|
||||
|
||||
PacketHeader header = new PacketHeader {
|
||||
Id = sender?.Id ?? Guid.Empty,
|
||||
Type = Constants.Packets[typeof(T)].Type,
|
||||
};
|
||||
FillPacket(header, packet, memory.Memory);
|
||||
await Broadcast(memory, sender);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes ownership of data and disposes once done.
|
||||
/// </summary>
|
||||
/// <param name="data">Memory owner to dispose once done</param>
|
||||
/// <param name="sender">Optional sender to not broadcast data to</param>
|
||||
public async Task Broadcast(IMemoryOwner<byte> data, Client? sender = null) {
|
||||
await Task.WhenAll(Clients.Where(c => c.Connected && c != sender).Select(client => client.Send(data.Memory)));
|
||||
data.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Broadcasts memory whose memory shouldn't be disposed, should only be fired by server code.
|
||||
/// </summary>
|
||||
/// <param name="data">Memory to send to the clients</param>
|
||||
/// <param name="sender">Optional sender to not broadcast data to</param>
|
||||
public async void Broadcast(Memory<byte> data, Client? sender = null) {
|
||||
await Task.WhenAll(Clients.Where(c => c.Connected && c != sender).Select(client => client.Send(data)));
|
||||
}
|
||||
|
||||
public Client? FindExistingClient(Guid id) {
|
||||
return Clients.Find(client => client.Id == id);
|
||||
}
|
||||
|
||||
|
||||
private async void HandleSocket(Socket socket) {
|
||||
Client client = new Client {Socket = socket};
|
||||
IMemoryOwner<byte> memory = null!;
|
||||
bool first = true;
|
||||
try {
|
||||
while (true) {
|
||||
memory = memoryPool.Rent(Constants.MaxPacketSize);
|
||||
int size = await socket.ReceiveAsync(memory.Memory, SocketFlags.None);
|
||||
if (size == 0) { // treat it as a disconnect and exit
|
||||
Logger.Info($"Socket {socket.RemoteEndPoint} disconnected.");
|
||||
await socket.DisconnectAsync(false);
|
||||
break;
|
||||
}
|
||||
|
||||
PacketHeader header = GetHeader(memory.Memory.Span[..size]);
|
||||
//Logger.Info($"first = {first}, type = {header.Type}, data = " + memory.Memory.Span[..size].Hex());
|
||||
// connection initialization
|
||||
if (first) {
|
||||
first = false;
|
||||
if (header.Type != PacketType.Connect) {
|
||||
throw new Exception($"First packet was not init, instead it was {header.Type}");
|
||||
}
|
||||
|
||||
ConnectPacket connect = MemoryMarshal.Read<ConnectPacket>(memory.Memory.Span[Constants.HeaderSize..size]);
|
||||
lock (Clients) {
|
||||
bool firstConn = false;
|
||||
switch (connect.ConnectionType) {
|
||||
case ConnectionTypes.FirstConnection: {
|
||||
firstConn = true;
|
||||
break;
|
||||
}
|
||||
case ConnectionTypes.Reconnecting: {
|
||||
if (FindExistingClient(header.Id) is { } newClient) {
|
||||
if (newClient.Connected) throw new Exception($"Tried to join as already connected user {header.Id}");
|
||||
newClient.Socket = client.Socket;
|
||||
client = newClient;
|
||||
} else {
|
||||
firstConn = true;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Exception($"Invalid connection type {connect.ConnectionType}");
|
||||
}
|
||||
if (firstConn) {
|
||||
// do any cleanup required when it comes to new clients
|
||||
List<Client> toDisconnect = Clients.FindAll(c => c.Id == header.Id && c.Connected && c.Socket != null);
|
||||
Clients.RemoveAll(c => c.Id == header.Id);
|
||||
|
||||
client.Id = header.Id;
|
||||
Clients.Add(client);
|
||||
|
||||
Parallel.ForEachAsync(toDisconnect, (c, token) => c.Socket!.DisconnectAsync(false, token));
|
||||
// Broadcast(connect, client);
|
||||
// done disconnecting and removing stale clients with the same id
|
||||
}
|
||||
}
|
||||
|
||||
Logger.Info($"Client {socket.RemoteEndPoint} connected.");
|
||||
|
||||
// continue;
|
||||
}
|
||||
|
||||
|
||||
// todo support variable length packets if they show up
|
||||
// Logger.Warn($"broadcasting {header.Type}");
|
||||
await Broadcast(memory, client);
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
if (e is SocketException {SocketErrorCode: SocketError.ConnectionReset}) {
|
||||
Logger.Info($"Client {socket.RemoteEndPoint} disconnected from the server");
|
||||
} else {
|
||||
Logger.Error($"Exception on socket {socket.RemoteEndPoint}, disconnecting for: {e}");
|
||||
await socket.DisconnectAsync(false);
|
||||
}
|
||||
|
||||
memory?.Dispose();
|
||||
}
|
||||
|
||||
Clients.Remove(client);
|
||||
Broadcast(new DisconnectPacket(), client).ContinueWith(_ => {
|
||||
client.Dispose();
|
||||
});
|
||||
}
|
||||
|
||||
private static PacketHeader GetHeader(Span<byte> data) {
|
||||
//no need to error check, the client will disconnect when the packet is invalid :)
|
||||
return MemoryMarshal.Read<PacketHeader>(data);
|
||||
}
|
||||
}
|
|
@ -1,19 +1,19 @@
|
|||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using Shared.Packet;
|
||||
using Shared.Packet.Packets;
|
||||
|
||||
namespace Shared;
|
||||
|
||||
public static class Constants {
|
||||
public const int MaxPacketSize = 256;
|
||||
public const int MaxClients = 4;
|
||||
public static int HeaderSize => Marshal.SizeOf<PacketHeader>();
|
||||
|
||||
// dictionary of packet types to packet
|
||||
public static readonly Dictionary<Type, PacketAttribute> Packets = Assembly
|
||||
.GetExecutingAssembly()
|
||||
.GetTypes()
|
||||
.Where(type => type.IsAssignableTo(typeof(IPacket)))
|
||||
.ToDictionary(type => type, type => type.GetCustomAttribute<PacketAttribute>()!);
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using Shared.Packet;
|
||||
using Shared.Packet.Packets;
|
||||
|
||||
namespace Shared;
|
||||
|
||||
public static class Constants {
|
||||
public const int MaxPacketSize = 256;
|
||||
public const int MaxClients = 4;
|
||||
public static int HeaderSize { get; } = Marshal.SizeOf<PacketHeader>();
|
||||
|
||||
// dictionary of packet types to packet
|
||||
public static readonly Dictionary<Type, PacketAttribute> Packets = Assembly
|
||||
.GetExecutingAssembly()
|
||||
.GetTypes()
|
||||
.Where(type => type.IsAssignableTo(typeof(IPacket)))
|
||||
.ToDictionary(type => type, type => type.GetCustomAttribute<PacketAttribute>()!);
|
||||
}
|
|
@ -1,10 +1,21 @@
|
|||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Shared.Packet;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct PacketHeader {
|
||||
public Guid Id;
|
||||
public PacketType Type;
|
||||
public PacketSender Sender;
|
||||
using System.Runtime.InteropServices;
|
||||
using Shared.Packet.Packets;
|
||||
|
||||
namespace Shared.Packet;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct PacketHeader : IPacket {
|
||||
// public int Length;
|
||||
public Guid Id;
|
||||
public PacketType Type;
|
||||
public void Serialize(Span<byte> data) {
|
||||
// MemoryMarshal.Write(data, ref Length);
|
||||
MemoryMarshal.Write(data, ref Id);
|
||||
MemoryMarshal.Write(data[16..], ref Type);
|
||||
}
|
||||
|
||||
public void Deserialize(Span<byte> data) {
|
||||
Id = MemoryMarshal.Read<Guid>(data);
|
||||
Type = MemoryMarshal.Read<PacketType>(data[16..]);
|
||||
}
|
||||
}
|
|
@ -1,6 +0,0 @@
|
|||
namespace Shared.Packet;
|
||||
|
||||
public enum PacketSender {
|
||||
Server,
|
||||
Client
|
||||
}
|
|
@ -1,12 +1,14 @@
|
|||
namespace Shared.Packet;
|
||||
|
||||
public enum PacketType {
|
||||
Unknown,
|
||||
Player,
|
||||
Game,
|
||||
Connect,
|
||||
Disconnect,
|
||||
Costume,
|
||||
Shine,
|
||||
Command
|
||||
namespace Shared.Packet;
|
||||
|
||||
public enum PacketType {
|
||||
Unknown,
|
||||
Player,
|
||||
Cap,
|
||||
Game,
|
||||
Tag,
|
||||
Connect,
|
||||
Disconnect,
|
||||
Costume,
|
||||
Shine,
|
||||
Command
|
||||
}
|
20
Shared/Packet/PacketUtils.cs
Normal file
20
Shared/Packet/PacketUtils.cs
Normal file
|
@ -0,0 +1,20 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using Shared.Packet.Packets;
|
||||
|
||||
namespace Shared.Packet;
|
||||
|
||||
public static class PacketUtils {
|
||||
public static void SerializeHeaded<T>(Span<byte> data, PacketHeader header, T t) where T : struct, IPacket {
|
||||
header.Serialize(data);
|
||||
t.Serialize(data[Constants.HeaderSize..]);
|
||||
}
|
||||
public static T Deserialize<T>(Span<byte> data) where T : IPacket, new() {
|
||||
T packet = new T();
|
||||
packet.Deserialize(data);
|
||||
return packet;
|
||||
}
|
||||
|
||||
public static int SizeOf<T>() where T : struct, IPacket {
|
||||
return Constants.HeaderSize + Marshal.SizeOf<T>();
|
||||
}
|
||||
}
|
|
@ -1,12 +1,13 @@
|
|||
namespace Shared.Packet.Packets;
|
||||
|
||||
[Packet(PacketType.Command)]
|
||||
public struct CommandPacket : IPacket {
|
||||
public void Serialize(Span<byte> data) {
|
||||
|
||||
}
|
||||
|
||||
public void Deserialize(Span<byte> data) {
|
||||
|
||||
}
|
||||
namespace Shared.Packet.Packets;
|
||||
|
||||
[Packet(PacketType.Command)]
|
||||
public struct CommandPacket : IPacket {
|
||||
//todo: implement something for this
|
||||
public void Serialize(Span<byte> data) {
|
||||
|
||||
}
|
||||
|
||||
public void Deserialize(Span<byte> data) {
|
||||
|
||||
}
|
||||
}
|
|
@ -1,15 +1,15 @@
|
|||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Shared.Packet.Packets;
|
||||
|
||||
[Packet(PacketType.Connect)]
|
||||
public struct ConnectPacket : IPacket {
|
||||
public ConnectionTypes ConnectionType;
|
||||
public void Serialize(Span<byte> data) {
|
||||
MemoryMarshal.Write(data, ref ConnectionType);
|
||||
}
|
||||
|
||||
public void Deserialize(Span<byte> data) {
|
||||
ConnectionType = MemoryMarshal.Read<ConnectionTypes>(data);
|
||||
}
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Shared.Packet.Packets;
|
||||
|
||||
[Packet(PacketType.Connect)]
|
||||
public struct ConnectPacket : IPacket {
|
||||
public ConnectionTypes ConnectionType;
|
||||
public void Serialize(Span<byte> data) {
|
||||
MemoryMarshal.Write(data, ref ConnectionType);
|
||||
}
|
||||
|
||||
public void Deserialize(Span<byte> data) {
|
||||
ConnectionType = MemoryMarshal.Read<ConnectionTypes>(data);
|
||||
}
|
||||
}
|
|
@ -1,22 +1,24 @@
|
|||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Shared.Packet.Packets;
|
||||
|
||||
[Packet(PacketType.Costume)]
|
||||
public struct CostumePacket : IPacket {
|
||||
public const int CostumeNameSize = 0x20;
|
||||
|
||||
public string BodyName;
|
||||
public string CapName;
|
||||
public void Serialize(Span<byte> data) {
|
||||
Span<char> strData = MemoryMarshal.Cast<byte, char>(data);
|
||||
BodyName.CopyTo(strData[..CostumeNameSize]);
|
||||
CapName.CopyTo(strData[CostumeNameSize..]);
|
||||
}
|
||||
|
||||
public void Deserialize(Span<byte> data) {
|
||||
Span<char> strData = MemoryMarshal.Cast<byte, char>(data);
|
||||
BodyName = new string(strData[..CostumeNameSize].TrimEnd('\0'));
|
||||
CapName = new string(strData[CostumeNameSize..].TrimEnd('\0'));
|
||||
}
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Shared.Packet.Packets;
|
||||
|
||||
[Packet(PacketType.Costume)]
|
||||
public struct CostumePacket : IPacket {
|
||||
public const int CostumeNameSize = 0x20;
|
||||
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CostumeNameSize)]
|
||||
public string BodyName;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CostumeNameSize)]
|
||||
public string CapName;
|
||||
public void Serialize(Span<byte> data) {
|
||||
Span<char> strData = MemoryMarshal.Cast<byte, char>(data);
|
||||
BodyName.CopyTo(strData[..CostumeNameSize]);
|
||||
CapName.CopyTo(strData[CostumeNameSize..]);
|
||||
}
|
||||
|
||||
public void Deserialize(Span<byte> data) {
|
||||
Span<char> strData = MemoryMarshal.Cast<byte, char>(data);
|
||||
BodyName = new string(strData[..CostumeNameSize].TrimEnd('\0'));
|
||||
CapName = new string(strData[CostumeNameSize..].TrimEnd('\0'));
|
||||
}
|
||||
}
|
|
@ -1,12 +1,13 @@
|
|||
namespace Shared.Packet.Packets;
|
||||
|
||||
[Packet(PacketType.Disconnect)]
|
||||
public struct DisconnectPacket : IPacket {
|
||||
public void Serialize(Span<byte> data) {
|
||||
|
||||
}
|
||||
|
||||
public void Deserialize(Span<byte> data) {
|
||||
|
||||
}
|
||||
namespace Shared.Packet.Packets;
|
||||
|
||||
[Packet(PacketType.Disconnect)]
|
||||
public struct DisconnectPacket : IPacket {
|
||||
//empty packet
|
||||
public void Serialize(Span<byte> data) {
|
||||
|
||||
}
|
||||
|
||||
public void Deserialize(Span<byte> data) {
|
||||
|
||||
}
|
||||
}
|
19
Shared/Packet/Packets/GamePacket.cs
Normal file
19
Shared/Packet/Packets/GamePacket.cs
Normal file
|
@ -0,0 +1,19 @@
|
|||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Shared.Packet.Packets;
|
||||
|
||||
public class GamePacket : IPacket {
|
||||
public int ScenarioNum;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = PlayerPacket.NameSize)]
|
||||
public string Stage;
|
||||
|
||||
public void Serialize(Span<byte> data) {
|
||||
MemoryMarshal.Write(data, ref ScenarioNum);
|
||||
Stage.CopyTo(MemoryMarshal.Cast<byte, char>(data[4..]));
|
||||
}
|
||||
|
||||
public void Deserialize(Span<byte> data) {
|
||||
ScenarioNum = MemoryMarshal.Read<int>(data);
|
||||
Stage = new string(MemoryMarshal.Cast<byte, char>(data[4..]));
|
||||
}
|
||||
}
|
|
@ -1,7 +1,9 @@
|
|||
namespace Shared.Packet.Packets;
|
||||
|
||||
// Packet interface for type safety
|
||||
public interface IPacket {
|
||||
void Serialize(Span<byte> data);
|
||||
void Deserialize(Span<byte> data);
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Shared.Packet.Packets;
|
||||
|
||||
// Packet interface for type safety
|
||||
public interface IPacket {
|
||||
void Serialize(Span<byte> data);
|
||||
void Deserialize(Span<byte> data);
|
||||
}
|
8
Shared/Packet/Packets/MovementFlags.cs
Normal file
8
Shared/Packet/Packets/MovementFlags.cs
Normal file
|
@ -0,0 +1,8 @@
|
|||
namespace Shared.Packet.Packets;
|
||||
|
||||
[Flags]
|
||||
public enum MovementFlags : byte {
|
||||
IsFlat,
|
||||
IsCapThrown,
|
||||
IsSeeker
|
||||
}
|
|
@ -1,60 +1,69 @@
|
|||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Shared.Packet.Packets;
|
||||
|
||||
[Packet(PacketType.Player)]
|
||||
public struct PlayerPacket : IPacket {
|
||||
public const int NameSize = 0x30;
|
||||
|
||||
public Vector3 Position;
|
||||
public Quaternion Rotation;
|
||||
public float[] AnimationBlendWeights;
|
||||
public float AnimationRate;
|
||||
public bool Flat;
|
||||
public bool ThrowingCap;
|
||||
public bool Seeker;
|
||||
public int ScenarioNum;
|
||||
public string Stage;
|
||||
public string Act;
|
||||
public string SubAct;
|
||||
|
||||
public void Serialize(Span<byte> data) {
|
||||
int offset = 0;
|
||||
MemoryMarshal.Write(data, ref Position);
|
||||
offset += Marshal.SizeOf<Vector3>();
|
||||
MemoryMarshal.Write(data[offset..], ref Rotation);
|
||||
offset += Marshal.SizeOf<Quaternion>();
|
||||
AnimationBlendWeights.CopyTo(MemoryMarshal.Cast<byte, float>(data[offset..(offset += 4 * 6)]));
|
||||
MemoryMarshal.Write(data[(offset += 4)..], ref AnimationRate);
|
||||
offset += 4;
|
||||
MemoryMarshal.Write(data[offset++..], ref Flat);
|
||||
MemoryMarshal.Write(data[offset++..], ref ThrowingCap);
|
||||
MemoryMarshal.Write(data[offset++..], ref Seeker);
|
||||
MemoryMarshal.Write(data[(offset += 4)..], ref ScenarioNum);
|
||||
Span<char> strData = MemoryMarshal.Cast<byte, char>(data[offset..]);
|
||||
Stage.CopyTo(strData[..NameSize]);
|
||||
Act.CopyTo(strData[NameSize..(2 * NameSize)]);
|
||||
SubAct.CopyTo(strData[(2 * NameSize)..(3 * NameSize)]);
|
||||
}
|
||||
|
||||
public void Deserialize(Span<byte> data) {
|
||||
int offset = 0;
|
||||
Position = MemoryMarshal.Read<Vector3>(data);
|
||||
offset += Marshal.SizeOf<Vector3>();
|
||||
Rotation = MemoryMarshal.Read<Quaternion>(data[offset..]);
|
||||
offset += Marshal.SizeOf<Quaternion>();
|
||||
AnimationBlendWeights = MemoryMarshal.Cast<byte, float>(data[offset..(offset + 4 * 6)]).ToArray();
|
||||
offset += 4 * 6;
|
||||
AnimationRate = MemoryMarshal.Read<float>(data[(offset += 4)..]);
|
||||
offset += 4;
|
||||
Flat = MemoryMarshal.Read<bool>(data[offset++..]);
|
||||
ThrowingCap = MemoryMarshal.Read<bool>(data[offset++..]);
|
||||
Seeker = MemoryMarshal.Read<bool>(data[offset++..]);
|
||||
ScenarioNum = MemoryMarshal.Read<int>(data[(offset += 4)..]);
|
||||
Span<char> strData = MemoryMarshal.Cast<byte, char>(data[offset..]);
|
||||
Stage = new string(strData[..NameSize].TrimEnd('\0'));
|
||||
Act = new string(strData[NameSize..(2 * NameSize)].TrimEnd('\0'));
|
||||
SubAct = new string(strData[(2 * NameSize)..(3 * NameSize)].TrimEnd('\0'));
|
||||
}
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace Shared.Packet.Packets;
|
||||
|
||||
[Packet(PacketType.Player)]
|
||||
public struct PlayerPacket : IPacket {
|
||||
public const int NameSize = 0x30;
|
||||
|
||||
public Vector3 Position;
|
||||
public Quaternion Rotation;
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
|
||||
public float[] AnimationBlendWeights;
|
||||
public float AnimationRate;
|
||||
public bool Is2d;
|
||||
public bool ThrowingCap;
|
||||
public bool IsIt;
|
||||
public int ScenarioNum;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NameSize)]
|
||||
public string Stage;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NameSize)]
|
||||
public string Act;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = NameSize)]
|
||||
public string SubAct;
|
||||
|
||||
public void Serialize(Span<byte> data) {
|
||||
int offset = 0;
|
||||
MemoryMarshal.Write(data, ref Position);
|
||||
offset += Marshal.SizeOf<Vector3>();
|
||||
MemoryMarshal.Write(data[offset..], ref Rotation);
|
||||
offset += Marshal.SizeOf<Quaternion>();
|
||||
AnimationBlendWeights.CopyTo(MemoryMarshal.Cast<byte, float>(data[offset..(offset += 4 * 6)]));
|
||||
MemoryMarshal.Write(data[offset..], ref AnimationRate);
|
||||
offset += 4;
|
||||
MemoryMarshal.Write(data[offset++..], ref Is2d);
|
||||
MemoryMarshal.Write(data[offset++..], ref ThrowingCap);
|
||||
MemoryMarshal.Write(data[offset++..], ref IsIt);
|
||||
MemoryMarshal.Write(data[offset..], ref ScenarioNum);
|
||||
offset += 5;
|
||||
// Span<char> strData = MemoryMarshal.Cast<byte, char>(data[offset..]);
|
||||
Encoding.UTF8.GetBytes(Stage).CopyTo(data[offset..(offset + NameSize)]);
|
||||
offset += NameSize;
|
||||
Encoding.UTF8.GetBytes(Act).CopyTo(data[offset..(offset + NameSize)]);
|
||||
offset += NameSize;
|
||||
Encoding.UTF8.GetBytes(SubAct).CopyTo(data[offset..]);
|
||||
}
|
||||
|
||||
public void Deserialize(Span<byte> data) {
|
||||
int offset = 0;
|
||||
Position = MemoryMarshal.Read<Vector3>(data);
|
||||
offset += Marshal.SizeOf<Vector3>();
|
||||
Rotation = MemoryMarshal.Read<Quaternion>(data[offset..]);
|
||||
offset += Marshal.SizeOf<Quaternion>();
|
||||
AnimationBlendWeights = MemoryMarshal.Cast<byte, float>(data[offset..(offset += 4 * 6)]).ToArray();
|
||||
AnimationRate = MemoryMarshal.Read<float>(data[offset..(offset += 4)]);
|
||||
Is2d = MemoryMarshal.Read<bool>(data[offset++..]);
|
||||
ThrowingCap = MemoryMarshal.Read<bool>(data[offset++..]);
|
||||
IsIt = MemoryMarshal.Read<bool>(data[offset++..]);
|
||||
// offset++; // padding
|
||||
ScenarioNum = MemoryMarshal.Read<int>(data[offset..]);
|
||||
offset += 5;
|
||||
Stage = new string(Encoding.UTF8.GetString(data[offset..(offset + NameSize)]).TrimEnd('\0'));
|
||||
offset += NameSize;
|
||||
Act = new string(Encoding.UTF8.GetString(data[offset..(offset + NameSize)]).TrimEnd('\0'));
|
||||
offset += NameSize;
|
||||
SubAct = new string(Encoding.UTF8.GetString(data[offset..(offset + NameSize)]).TrimEnd('\0'));
|
||||
}
|
||||
}
|
|
@ -1,13 +1,13 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.Numerics.Vectors" Version="4.5.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.Numerics.Vectors" Version="4.5.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
@ -8,18 +8,48 @@ using Shared.Packet;
|
|||
using Shared.Packet.Packets;
|
||||
|
||||
TcpClient client = new TcpClient("127.0.0.1", 1027);
|
||||
Guid ownId = new Guid();
|
||||
Guid ownId = new Guid(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
||||
Guid otherId = Guid.Empty;
|
||||
Logger logger = new Logger("Client");
|
||||
NetworkStream stream = client.GetStream();
|
||||
PacketHeader coolHeader = new PacketHeader {
|
||||
Type = PacketType.Connect,
|
||||
Sender = PacketSender.Client,
|
||||
Id = ownId
|
||||
};
|
||||
|
||||
int e = 0;
|
||||
double d = 0;
|
||||
Vector3 basePoint = Vector3.Zero;
|
||||
PlayerPacket? playerPacket = null;
|
||||
|
||||
async void Funny() {
|
||||
Memory<byte> memory = new Memory<byte>(new byte[256]);
|
||||
|
||||
{
|
||||
PacketHeader header = new PacketHeader {
|
||||
Id = ownId,
|
||||
Type = PacketType.Player
|
||||
};
|
||||
MemoryMarshal.Write(memory.Span, ref header);
|
||||
}
|
||||
|
||||
while (true) {
|
||||
d += Math.PI / 32;
|
||||
if (playerPacket == null) {
|
||||
// logger.Warn($"Waiting...");
|
||||
await Task.Delay(300);
|
||||
continue;
|
||||
}
|
||||
|
||||
PlayerPacket packet = playerPacket.Value;
|
||||
Vector3 pos = basePoint;
|
||||
pos.X += 100f * (float) Math.Cos(d);
|
||||
pos.Y += 300f;
|
||||
pos.Z += 100f * (float) Math.Sin(d);
|
||||
packet.Position = pos;
|
||||
packet.Serialize(memory.Span[Constants.HeaderSize..]);
|
||||
logger.Warn($"Current strs:{packet.Stage}-{packet.Act}-{packet.SubAct} {packet.Is2d} {packet.ThrowingCap} {packet.IsIt}");
|
||||
|
||||
await stream.WriteAsync(memory);
|
||||
await Task.Delay(50);
|
||||
}
|
||||
}
|
||||
|
||||
async Task S() {
|
||||
IMemoryOwner<byte> owner = MemoryPool<byte>.Shared.Rent(256);
|
||||
|
@ -34,23 +64,26 @@ async Task S() {
|
|||
continue;
|
||||
}
|
||||
|
||||
d += Math.PI / 180;
|
||||
header.Id = ownId;
|
||||
MemoryMarshal.Write(owner.Memory.Span, ref header);
|
||||
unsafe {
|
||||
MemoryMarshal.Write(owner.Memory.Span, ref coolHeader);
|
||||
// unbelievably shitty way to marshal playerpacket
|
||||
fixed (byte* basePtr = owner.Memory.Span) {
|
||||
byte* dataPtr = basePtr + Constants.HeaderSize;
|
||||
Vector3 pos = Unsafe.Read<Vector3>(dataPtr);
|
||||
pos.X += 1000f * (float)Math.Cos(d);
|
||||
pos.Z += 1000f * (float)Math.Sin(d);
|
||||
Unsafe.Write(dataPtr, pos);
|
||||
fixed (byte* data = owner.Memory.Span[Constants.HeaderSize..]) {
|
||||
logger.Error($"{Marshal.OffsetOf<PlayerPacket>(nameof(PlayerPacket.AnimationBlendWeights))} {Marshal.OffsetOf<PlayerPacket>(nameof(PlayerPacket.AnimationRate))}");
|
||||
PlayerPacket packet = Marshal.PtrToStructure<PlayerPacket>((IntPtr) data);
|
||||
playerPacket = packet;
|
||||
basePoint = packet.Position;
|
||||
}
|
||||
}
|
||||
Console.WriteLine($"aargh {coolHeader.Id} {owner.Memory.Span[..256].Hex()}");
|
||||
await stream.WriteAsync(owner.Memory);
|
||||
|
||||
// packet.SubAct = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PacketHeader coolHeader = new PacketHeader {
|
||||
Type = PacketType.Connect,
|
||||
Id = ownId
|
||||
};
|
||||
IMemoryOwner<byte> owner = MemoryPool<byte>.Shared.Rent(256);
|
||||
MemoryMarshal.Write(owner.Memory.Span[..], ref coolHeader);
|
||||
ConnectPacket connect = new ConnectPacket {
|
||||
|
@ -60,4 +93,6 @@ MemoryMarshal.Write(owner.Memory.Span[Constants.HeaderSize..256], ref connect);
|
|||
await stream.WriteAsync(owner.Memory);
|
||||
coolHeader.Type = PacketType.Player;
|
||||
MemoryMarshal.Write(owner.Memory.Span[..], ref coolHeader);
|
||||
logger.Info("Connected");
|
||||
Task.Run(Funny);
|
||||
await S();
|
Loading…
Reference in a new issue