Initial version

This commit is contained in:
2025-12-16 06:16:55 +01:00
parent 53783498c5
commit 76c4cd2000
15 changed files with 1310 additions and 42 deletions

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.FastWriter\EonaCat.FastWriter.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,122 @@
using EonaCat.FastWriter;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
internal class Program
{
private static async Task Main(string[] args)
{
// Test serialization for simple objects
var user = new User
{
Id = 1,
Name = "Alice",
IsAdmin = true,
Home = new Address { Street = "123 Main St", City = "Wonderland" }
};
byte[] data1 = FastSerializer.Serialize(user);
User clone = FastSerializer.Deserialize<User>(data1);
Console.WriteLine($"User clone: {clone.Name}, Admin={clone.IsAdmin}, City={clone.Home.City}");
// Test big collections
var numbers = new List<int>();
for (int i = 0; i < 100_000; i++)
{
numbers.Add(i);
}
byte[] data2 = FastSerializer.Serialize(numbers);
var copy1 = FastSerializer.Deserialize<List<int>>(data2);
Console.WriteLine($"Big list count: {copy1.Count}, First={copy1[0]}, Last={copy1[^1]}");
// Test array of strings
string[] names = { "A", "B", "C", "D", "E" };
var data3 = FastSerializer.Serialize(names);
var copy2 = FastSerializer.Deserialize<string[]>(data3);
Console.WriteLine($"String array length: {copy2.Length}, Second={copy2[1]}");
// Test nested collections
var users = new List<User>();
for (int i = 0; i < 10; i++)
{
users.Add(new User
{
Id = i,
Name = $"User{i}",
IsAdmin = i % 2 == 0,
Home = new Address { Street = $"Street {i}", City = $"City {i}" }
});
}
byte[] data4 = FastSerializer.Serialize(users);
var copy3 = FastSerializer.Deserialize<List<User>>(data4);
Console.WriteLine($"Nested list count: {copy3.Count}, Last user city: {copy3[^1].Home.City}");
// Test dictionary
var dict = new Dictionary<string, User>();
for (int i = 0; i < 5; i++)
{
dict[$"key{i}"] = new User { Id = i, Name = $"DUser{i}", Home = new Address { Street = $"S{i}", City = $"C{i}" } };
}
byte[] data5 = FastSerializer.Serialize(dict);
var copy4 = FastSerializer.Deserialize<Dictionary<string, User>>(data5);
Console.WriteLine($"Dictionary count: {copy4.Count}, key2 user name: {copy4["key2"].Name}");
// Server and Client test with messages
var server = new Server<Message>(12345);
server.MessageReceived += async (msg, client) =>
{
Console.WriteLine($"Server received: {msg.Text}, Number={msg.Number}");
await server.SendAsync(new Message { Text = "Ack: " + msg.Text, Number = msg.Number }, client);
};
_ = server.StartAsync();
var client = new Client<Message>("127.0.0.1", 12345);
client.MessageReceived += async msg =>
{
Console.WriteLine($"Client received: {msg.Text}, Number={msg.Number}");
await client.SendAsync(new Message { Text = $"Got your {msg.Number}", Number = 999 });
};
await client.ConnectAsync();
await client.SendAsync(new Message { Text = "Hello Server", Number = 123 });
// Send nested objects and big collections through server
await client.SendAsync(new Message { Text = $"Nested test: {copy3[0].Name}", Number = copy3.Count });
await client.SendAsync(new Message { Text = $"Big list last value: {copy1[^1]}", Number = copy1.Count });
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
public class Address
{
public string Street { get; set; } = "";
public string City { get; set; } = "";
}
public class User
{
public int Id { get; set; }
public string Name { get; set; } = "";
public bool IsAdmin { get; set; }
public Address Home { get; set; } = new Address();
}
public class Message
{
public string Text { get; set; } = "";
public int Number { get; set; }
}

View File

@@ -0,0 +1,4 @@
<Solution>
<Project Path="EonaCat.FastWriter.Testers/EonaCat.FastWriter.Testers.csproj" />
<Project Path="EonaCat.FastWriter/EonaCat.FastWriter.csproj" />
</Solution>

View File

@@ -0,0 +1,199 @@
namespace EonaCat.FastWriter;
using System;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class Client<T>
{
private readonly string _host;
private readonly int _port;
private TcpClient? _client;
private NetworkStream? _stream;
private readonly bool _autoReconnect;
private readonly int _reconnectDelayMs;
private readonly bool _useRaw;
private CancellationTokenSource _cts = new();
public string Nickname { get; private set; } = Guid.NewGuid().ToString();
// Events
public event Action<T>? MessageReceived;
public event Action<byte[]>? RawMessageReceived;
public event Action? Connected;
public event Action? Disconnected;
public Client(string host, int port, bool autoReconnect = true, int reconnectDelayMs = 3000, string? nickname = null, bool useRaw = false)
{
_host = host;
_port = port;
_autoReconnect = autoReconnect;
_reconnectDelayMs = reconnectDelayMs;
_useRaw = useRaw; // store raw mode
if (!string.IsNullOrEmpty(nickname))
{
Nickname = nickname;
}
}
public async Task ConnectAsync()
{
_cts = new CancellationTokenSource();
await ConnectInternalAsync(_cts.Token);
}
private async Task ConnectInternalAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
_client = new TcpClient();
await _client.ConnectAsync(_host, _port);
_stream = _client.GetStream();
Connected?.Invoke();
// Start receiving messages automatically in the chosen mode
_ = ReceiveLoopAsync(token);
return;
}
catch
{
Disconnected?.Invoke();
if (!_autoReconnect)
{
throw;
}
await Task.Delay(_reconnectDelayMs, token);
}
}
}
public async Task SendAsync(T msg)
{
if (_useRaw)
{
throw new InvalidOperationException("Client is in raw mode; use SendRawAsync instead.");
}
if (_stream == null || _client == null || !_client.Connected)
{
if (_autoReconnect)
{
await ConnectInternalAsync(_cts.Token);
}
else
{
throw new InvalidOperationException("Client not connected");
}
}
byte[] data = FastSerializer.Serialize(msg);
byte[] lenBytes = BitConverter.GetBytes(data.Length);
await _stream.WriteAsync(lenBytes, 0, lenBytes.Length);
await _stream.WriteAsync(data, 0, data.Length);
}
public async Task SendRawAsync(byte[] data)
{
if (!_useRaw)
{
throw new InvalidOperationException("Client is not in raw mode; use SendAsync<T> instead.");
}
if (_stream == null || _client == null || !_client.Connected)
{
if (_autoReconnect)
{
await ConnectInternalAsync(_cts.Token);
}
else
{
throw new InvalidOperationException("Client not connected");
}
}
await _stream.WriteAsync(data, 0, data.Length);
}
private async Task ReceiveLoopAsync(CancellationToken token)
{
if (_stream == null)
{
return;
}
var stream = _stream;
try
{
while (!token.IsCancellationRequested)
{
if (_useRaw)
{
var buffer = new byte[4096];
int read = await stream.ReadAsync(buffer, 0, buffer.Length, token);
if (read == 0)
{
break; // disconnected
}
byte[] received = new byte[read];
Array.Copy(buffer, 0, received, 0, read);
RawMessageReceived?.Invoke(received);
}
else
{
byte[] lenBytes = new byte[4];
int read = await stream.ReadAsync(lenBytes, 0, 4, token);
if (read == 0)
{
break;
}
int length = BitConverter.ToInt32(lenBytes, 0);
byte[] data = new byte[length];
int totalRead = 0;
while (totalRead < length)
{
totalRead += await stream.ReadAsync(data, totalRead, length - totalRead, token);
}
var msg = FastSerializer.Deserialize<T>(data);
MessageReceived?.Invoke(msg);
}
}
}
catch
{
// connection lost
}
finally
{
Disconnected?.Invoke();
_client?.Close();
_stream = null;
if (_autoReconnect && !token.IsCancellationRequested)
{
await ConnectInternalAsync(token);
}
}
}
public void Disconnect()
{
_cts.Cancel();
_stream?.Close();
_client?.Close();
}
public void SetNickname(string nickname) => Nickname = nickname;
}

View File

@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<PackageId>EonaCat.FastWriter</PackageId>
<Title>EonaCat.FastWriter</Title>
<Authors>EonaCat (Jeroen Saey)</Authors>
<Company>EonaCat</Company>
<Copyright>EonaCat (Jeroen Saey)</Copyright>
<PackageProjectUrl>https://git.saey.me/EonaCat/EonaCat.FastWriter</PackageProjectUrl>
<RepositoryUrl>https://git.saey.me/EonaCat/EonaCat.FastWriter</RepositoryUrl>
<PackageReadmeFile>readme.md</PackageReadmeFile>
<PackageIcon>icon.png</PackageIcon>
<RepositoryType>git</RepositoryType>
<PackageTags>fast;writer;serialize;deserialize;EonaCat;Jeroen;Saey;binary;Speed;performance</PackageTags>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
</PropertyGroup>
<ItemGroup>
<None Include="..\..\icon.png">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Include="..\..\LICENSE">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Include="..\..\readme.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,44 @@
using System.Text;
namespace EonaCat.FastWriter;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
using System;
internal ref struct FastReader
{
private readonly ReadOnlySpan<byte> _span;
private int _pos;
public FastReader(ReadOnlySpan<byte> span) { _span = span; _pos = 0; }
public byte ReadByte() => _span[_pos++];
public int ReadInt() { int result = 0, shift = 0; byte b; do { b = ReadByte(); result |= (b & 0x7F) << shift; shift += 7; } while ((b & 0x80) != 0); return result; }
public long ReadInt64() { long result = 0; int shift = 0; byte b; do { b = ReadByte(); result |= ((long)(b & 0x7F)) << shift; shift += 7; } while ((b & 0x80) != 0); return result; }
public string? ReadString()
{
int len = ReadInt();
if (len < 0)
{
return null;
}
var s = Encoding.UTF8.GetString(_span.Slice(_pos, len));
_pos += len;
return s;
}
// Primitive support
public bool ReadBool() => ReadByte() != 0;
public byte ReadByteValue() => ReadByte();
public sbyte ReadSByte() => (sbyte)ReadByte();
public short ReadShort() => (short)ReadInt();
public ushort ReadUShort() => (ushort)ReadInt();
public uint ReadUInt() => (uint)ReadInt();
public long ReadLong() => ReadInt64();
public ulong ReadULong() => (ulong)ReadInt64();
public float ReadFloat() => BitConverter.Int32BitsToSingle(ReadInt());
public double ReadDouble() => BitConverter.Int64BitsToDouble(ReadInt64());
public char ReadChar() => (char)ReadInt();
}

View File

@@ -0,0 +1,26 @@
using System.Buffers;
namespace EonaCat.FastWriter;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
using EonaCat.FastWriter.Models;
using System;
public static class FastSerializer
{
public static byte[] Serialize<T>(T value)
{
var buffer = new ArrayBufferWriter<byte>();
var writer = new FastWriter(buffer);
Dispatcher.Write(ref writer, value, typeof(T));
return buffer.WrittenSpan.ToArray();
}
public static T Deserialize<T>(ReadOnlySpan<byte> data)
{
var reader = new FastReader(data);
return (T)Dispatcher.Read(ref reader, typeof(T))!;
}
}

View File

@@ -0,0 +1,42 @@
using System.Buffers;
using System.Text;
namespace EonaCat.FastWriter;
using System;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
internal ref struct FastWriter
{
private readonly IBufferWriter<byte> _buffer;
public FastWriter(IBufferWriter<byte> buffer) => _buffer = buffer;
public void WriteByte(byte v) { var s = _buffer.GetSpan(1); s[0] = v; _buffer.Advance(1); }
public void WriteInt(int value) { uint v = (uint)value; while (v >= 0x80) { WriteByte((byte)(v | 0x80)); v >>= 7; } WriteByte((byte)v); }
public void WriteInt64(long value) { ulong v = (ulong)value; while (v >= 0x80) { WriteByte((byte)(v | 0x80)); v >>= 7; } WriteByte((byte)v); }
public void WriteString(string? value)
{
if (value == null) { WriteInt(-1); return; }
int byteCount = Encoding.UTF8.GetByteCount(value);
WriteInt(byteCount);
var span = _buffer.GetSpan(byteCount);
Encoding.UTF8.GetBytes(value.AsSpan(), span);
_buffer.Advance(byteCount);
}
// Primitive support
public void WriteBool(bool v) => WriteByte(v ? (byte)1 : (byte)0);
public void WriteByteValue(byte v) => WriteByte(v);
public void WriteSByte(sbyte v) => WriteByte((byte)v);
public void WriteShort(short v) => WriteInt(v);
public void WriteUShort(ushort v) => WriteInt(v);
public void WriteUInt(uint v) => WriteInt((int)v);
public void WriteLong(long v) => WriteInt64(v);
public void WriteULong(ulong v) => WriteInt64((long)v);
public void WriteFloat(float v) => WriteInt(BitConverter.SingleToInt32Bits(v));
public void WriteDouble(double v) => WriteInt64(BitConverter.DoubleToInt64Bits(v));
public void WriteChar(char v) => WriteInt(v);
}

View File

@@ -0,0 +1,212 @@
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace EonaCat.FastWriter.Models;
using System;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
internal static class Dispatcher
{
private static readonly ConcurrentDictionary<Type, TypeModel> Models = new();
public static void Write(ref FastWriter w, object? value, Type type)
{
if (value == null) { w.WriteByte(0); return; }
w.WriteByte(1);
if (TryWritePrimitive(ref w, value, type))
{
return;
}
if (typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string))
{
WriteEnumerable(ref w, (IEnumerable)value, type);
return;
}
WriteObject(ref w, value, type);
}
public static object? Read(ref FastReader r, Type type)
{
if (r.ReadByte() == 0)
{
return null;
}
if (TryReadPrimitive(ref r, type, out var value))
{
return value;
}
if (typeof(IEnumerable).IsAssignableFrom(type) && type != typeof(string))
{
return ReadEnumerable(ref r, type);
}
return ReadObject(ref r, type);
}
private static bool TryWritePrimitive(ref FastWriter w, object value, Type type)
{
if (type == typeof(bool)) { w.WriteBool((bool)value); return true; }
if (type == typeof(byte)) { w.WriteByteValue((byte)value); return true; }
if (type == typeof(sbyte)) { w.WriteSByte((sbyte)value); return true; }
if (type == typeof(short)) { w.WriteShort((short)value); return true; }
if (type == typeof(ushort)) { w.WriteUShort((ushort)value); return true; }
if (type == typeof(int)) { w.WriteInt((int)value); return true; }
if (type == typeof(uint)) { w.WriteUInt((uint)value); return true; }
if (type == typeof(long)) { w.WriteLong((long)value); return true; }
if (type == typeof(ulong)) { w.WriteULong((ulong)value); return true; }
if (type == typeof(float)) { w.WriteFloat((float)value); return true; }
if (type == typeof(double)) { w.WriteDouble((double)value); return true; }
if (type == typeof(char)) { w.WriteChar((char)value); return true; }
if (type == typeof(string)) { w.WriteString((string)value); return true; }
if (type.IsEnum) { w.WriteInt(Convert.ToInt32(value)); return true; }
return false;
}
private static bool TryReadPrimitive(ref FastReader r, Type type, out object? value)
{
value = type switch
{
Type t when t == typeof(bool) => r.ReadBool(),
Type t when t == typeof(byte) => r.ReadByteValue(),
Type t when t == typeof(sbyte) => r.ReadSByte(),
Type t when t == typeof(short) => r.ReadShort(),
Type t when t == typeof(ushort) => r.ReadUShort(),
Type t when t == typeof(int) => r.ReadInt(),
Type t when t == typeof(uint) => r.ReadUInt(),
Type t when t == typeof(long) => r.ReadLong(),
Type t when t == typeof(ulong) => r.ReadULong(),
Type t when t == typeof(float) => r.ReadFloat(),
Type t when t == typeof(double) => r.ReadDouble(),
Type t when t == typeof(char) => r.ReadChar(),
Type t when t == typeof(string) => r.ReadString(),
Type t when t.IsEnum => Enum.ToObject(t, r.ReadInt()),
_ => null
};
return value != null;
}
private static void WriteObject(ref FastWriter w, object obj, Type type)
{
var model = Models.GetOrAdd(type, t => new TypeModel(t));
w.WriteInt(model.Properties.Length);
foreach (var p in model.Properties)
{
int id = TypeModel.GetFieldId(p);
w.WriteInt(id);
var value = model.Accessors[id].Getter(obj);
Write(ref w, value, p.PropertyType);
}
}
private static object ReadObject(ref FastReader r, Type type)
{
var model = Models.GetOrAdd(type, t => new TypeModel(t));
var obj = model.ObjectCreator();
int count = r.ReadInt();
for (int i = 0; i < count; i++)
{
int id = r.ReadInt();
if (model.Accessors.TryGetValue(id, out var accessor))
{
accessor.Setter(obj, Read(ref r, accessor.PropertyType));
}
else
{
Skip(ref r);
}
}
return obj;
}
private static void WriteEnumerable(ref FastWriter w, IEnumerable value, Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
var dictType = type;
var keyType = dictType.GetGenericArguments()[0];
var valueType = dictType.GetGenericArguments()[1];
var dict = (System.Collections.IDictionary)value;
w.WriteInt(dict.Count);
foreach (System.Collections.DictionaryEntry entry in dict)
{
Write(ref w, entry.Key, keyType);
Write(ref w, entry.Value, valueType);
}
return;
}
// normal IEnumerable handling
var list = value.Cast<object?>().ToList();
w.WriteInt(list.Count);
var elemType = type.IsArray ? type.GetElementType()! : type.GetGenericArguments()[0];
foreach (var i in list)
{
Write(ref w, i, elemType);
}
}
private static object ReadEnumerable(ref FastReader r, Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
var dictType = type;
var keyType = dictType.GetGenericArguments()[0];
var valueType = dictType.GetGenericArguments()[1];
int count = r.ReadInt();
var dict = (System.Collections.IDictionary)Activator.CreateInstance(type)!;
for (int i = 0; i < count; i++)
{
var key = Read(ref r, keyType);
var value = Read(ref r, valueType);
dict.Add(key, value);
}
return dict;
}
// normal IEnumerable handling
int length = r.ReadInt();
var elemType = type.IsArray ? type.GetElementType()! : type.GetGenericArguments()[0];
var list = (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(elemType))!;
for (int i = 0; i < length; i++)
{
list.Add(Read(ref r, elemType));
}
if (type.IsArray)
{
var array = Array.CreateInstance(elemType, list.Count);
for (int i = 0; i < list.Count; i++)
{
array.SetValue(list[i], i);
}
return array;
}
return list;
}
private static void Skip(ref FastReader r)
{
if (r.ReadByte() == 0)
{
return;
}
r.ReadString();
}
}

View File

@@ -0,0 +1,41 @@
using System.Linq.Expressions;
using System.Reflection;
namespace EonaCat.FastWriter.Models;
using System;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
internal sealed class PropertyAccessor
{
public readonly Action<object, object?> Setter;
public readonly Func<object, object?> Getter;
public readonly Type PropertyType;
public PropertyAccessor(PropertyInfo prop)
{
PropertyType = prop.PropertyType;
Setter = CreateSetter(prop);
Getter = CreateGetter(prop);
}
private static Action<object, object?> CreateSetter(PropertyInfo prop)
{
var objParam = Expression.Parameter(typeof(object), "obj");
var valParam = Expression.Parameter(typeof(object), "val");
var castObj = Expression.Convert(objParam, prop.DeclaringType!);
var castVal = Expression.Convert(valParam, prop.PropertyType);
var body = Expression.Assign(Expression.Property(castObj, prop), castVal);
return Expression.Lambda<Action<object, object?>>(body, objParam, valParam).Compile();
}
private static Func<object, object?> CreateGetter(PropertyInfo prop)
{
var objParam = Expression.Parameter(typeof(object), "obj");
var castObj = Expression.Convert(objParam, prop.DeclaringType!);
var body = Expression.Convert(Expression.Property(castObj, prop), typeof(object));
return Expression.Lambda<Func<object, object?>>(body, objParam).Compile();
}
}

View File

@@ -0,0 +1,51 @@
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace EonaCat.FastWriter.Models;
using System;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
internal sealed class TypeModel
{
public readonly PropertyInfo[] Properties;
public readonly Dictionary<int, PropertyAccessor> Accessors;
public readonly Func<object> ObjectCreator;
public TypeModel(Type type)
{
Properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead && p.CanWrite)
.OrderBy(p => p.Name)
.ToArray();
Accessors = Properties.ToDictionary(
p => GetFieldId(p),
p => new PropertyAccessor(p)
);
ObjectCreator = CreateObjectActivator(type);
}
private static Func<object> CreateObjectActivator(Type type)
{
if (type.IsValueType)
{
return () => Activator.CreateInstance(type)!;
}
var ctor = type.GetConstructor(Type.EmptyTypes);
if (ctor != null)
{
return () => Activator.CreateInstance(type)!;
}
return () => System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);
}
public static int GetFieldId(PropertyInfo p) => p.Name.GetHashCode(StringComparison.Ordinal);
}

View File

@@ -0,0 +1,187 @@
using System.Collections.Concurrent;
namespace EonaCat.FastWriter;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
public class Server<T>
{
private readonly int _port;
private TcpListener? _listener;
private readonly bool _useRaw;
// Thread-safe storage of connected clients
private readonly ConcurrentDictionary<TcpClient, NetworkStream> _clients = new();
private readonly ConcurrentDictionary<TcpClient, string> _nicknames = new();
// Events
public event Action<T, TcpClient>? MessageReceived;
public event Action<byte[], TcpClient>? RawMessageReceived; // new
public event Action<TcpClient, string?>? ClientConnected;
public event Action<TcpClient, string?>? ClientDisconnected;
public Server(int port, bool useRaw = false)
{
_port = port;
_useRaw = useRaw;
}
public async Task StartAsync()
{
_listener = new TcpListener(IPAddress.Any, _port);
_listener.Start();
Console.WriteLine($"Server listening on port {_port}");
while (true)
{
var client = await _listener.AcceptTcpClientAsync();
var stream = client.GetStream();
_clients[client] = stream;
string? nickname = null;
_nicknames[client] = nickname;
ClientConnected?.Invoke(client, nickname);
_ = HandleClientAsync(client, stream); // fire-and-forget
}
}
private async Task HandleClientAsync(TcpClient client, NetworkStream stream)
{
try
{
while (true)
{
if (_useRaw)
{
var buffer = new byte[4096];
int read = await stream.ReadAsync(buffer, 0, buffer.Length);
if (read == 0)
{
break; // disconnected
}
byte[] received = new byte[read];
Array.Copy(buffer, 0, received, 0, read);
RawMessageReceived?.Invoke(received, client);
}
else
{
// length-prefixed typed messages
byte[] lenBytes = new byte[4];
int read = await stream.ReadAsync(lenBytes, 0, 4);
if (read == 0)
{
break; // disconnected
}
int length = BitConverter.ToInt32(lenBytes, 0);
byte[] data = new byte[length];
int totalRead = 0;
while (totalRead < length)
{
totalRead += await stream.ReadAsync(data, totalRead, length - totalRead);
}
var msg = FastSerializer.Deserialize<T>(data);
MessageReceived?.Invoke(msg, client);
}
}
}
catch
{
// connection lost
}
finally
{
_clients.TryRemove(client, out _);
_nicknames.TryRemove(client, out var nick);
ClientDisconnected?.Invoke(client, nick);
client.Close();
}
}
// Send typed message
public async Task SendAsync(T msg, TcpClient client)
{
if (_useRaw)
{
throw new InvalidOperationException("Server is in raw mode; use SendRawAsync instead.");
}
if (!_clients.TryGetValue(client, out var stream))
{
return;
}
byte[] data = FastSerializer.Serialize(msg);
byte[] lenBytes = BitConverter.GetBytes(data.Length);
await stream.WriteAsync(lenBytes, 0, lenBytes.Length);
await stream.WriteAsync(data, 0, data.Length);
}
// Send raw bytes
public async Task SendRawAsync(byte[] data, TcpClient client)
{
if (!_useRaw)
{
throw new InvalidOperationException("Server is not in raw mode; use SendAsync<T> instead.");
}
if (!_clients.TryGetValue(client, out var stream))
{
return;
}
await stream.WriteAsync(data, 0, data.Length);
}
// Broadcast typed message
public async Task BroadcastAsync(T msg)
{
foreach (var kv in _clients)
{
try { await SendAsync(msg, kv.Key); } catch { }
}
}
// Broadcast raw bytes
public async Task BroadcastRawAsync(byte[] data)
{
foreach (var kv in _clients)
{
try { await SendRawAsync(data, kv.Key); } catch { }
}
}
// Optional: send by nickname (typed)
public async Task SendToNicknameAsync(T msg, string nickname)
{
foreach (var kv in _nicknames)
{
if (kv.Value == nickname)
{
await SendAsync(msg, kv.Key);
break;
}
}
}
public void SetClientNickname(TcpClient client, string nickname)
{
if (_clients.ContainsKey(client))
{
_nicknames[client] = nickname;
}
}
public void Stop() => _listener?.Stop();
}

181
LICENSE
View File

@@ -1,64 +1,195 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
https://EonaCat.com/license/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
OF SOFTWARE BY EONACAT (JEROEN SAEY)
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025 EonaCat
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

160
README.md
View File

@@ -1,3 +1,161 @@
# EonaCat.FastWriter
EonaCat.FastWriter
A high-performance serialization library.
Custom serializer for maximum speed and minimal allocations.
---
Optional Tcp server and client with auto-reconnect and broadcast support.
## Features
- **Typed messaging**: Send/receive objects of any type `T` using a fast custom serializer.
- **Raw byte messaging**: Send/receive arbitrary byte arrays for raw TCP servers/clients.
- **Dynamic mode switching**: Both server and client can switch between typed and raw mode at runtime using the `UseRaw` property.
- **Auto-reconnect**: Client automatically reconnects on connection loss.
- **Broadcast**: Send messages to all connected clients.
- **Nicknames**: Optional support for assigning nicknames to clients.
---
## Installation
```csharp
Install-Package EonaCat.FastWriter
```
Include the `EonaCat.FastWriter` namespace and all relevant classes in your project:
- `Server<T>`
- `Client<T>`
- `FastSerializer`, `FastReader`, `FastWriter`, `Dispatcher`
No external dependencies required.
---
## Usage
# Example application:
```csharp
using EonaCat.FastWriter;
internal class Program
{
private static async Task Main(string[] args)
{
// Test serialization for simple objects
var user = new User
{
Id = 1,
Name = "Alice",
IsAdmin = true,
Home = new Address { Street = "123 Main St", City = "Wonderland" }
};
byte[] data1 = FastSerializer.Serialize(user);
User clone = FastSerializer.Deserialize<User>(data1);
Console.WriteLine($"User clone: {clone.Name}, Admin={clone.IsAdmin}, City={clone.Home.City}");
// Test big collections
var numbers = new List<int>();
for (int i = 0; i < 100_000; i++)
{
numbers.Add(i);
}
byte[] data2 = FastSerializer.Serialize(numbers);
var copy1 = FastSerializer.Deserialize<List<int>>(data2);
Console.WriteLine($"Big list count: {copy1.Count}, First={copy1[0]}, Last={copy1[^1]}");
// Test array of strings
string[] names = { "A", "B", "C", "D", "E" };
var data3 = FastSerializer.Serialize(names);
var copy2 = FastSerializer.Deserialize<string[]>(data3);
Console.WriteLine($"String array length: {copy2.Length}, Second={copy2[1]}");
// Test nested collections
var users = new List<User>();
for (int i = 0; i < 10; i++)
{
users.Add(new User
{
Id = i,
Name = $"User{i}",
IsAdmin = i % 2 == 0,
Home = new Address { Street = $"Street {i}", City = $"City {i}" }
});
}
byte[] data4 = FastSerializer.Serialize(users);
var copy3 = FastSerializer.Deserialize<List<User>>(data4);
Console.WriteLine($"Nested list count: {copy3.Count}, Last user city: {copy3[^1].Home.City}");
// Test dictionary
var dict = new Dictionary<string, User>();
for (int i = 0; i < 5; i++)
{
dict[$"key{i}"] = new User { Id = i, Name = $"DUser{i}", Home = new Address { Street = $"S{i}", City = $"C{i}" } };
}
byte[] data5 = FastSerializer.Serialize(dict);
var copy4 = FastSerializer.Deserialize<Dictionary<string, User>>(data5);
Console.WriteLine($"Dictionary count: {copy4.Count}, key2 user name: {copy4["key2"].Name}");
// Server and Client test with messages
var server = new Server<Message>(12345);
server.MessageReceived += async (msg, client) =>
{
Console.WriteLine($"Server received: {msg.Text}, Number={msg.Number}");
await server.SendAsync(new Message { Text = "Ack: " + msg.Text, Number = msg.Number }, client);
};
_ = server.StartAsync();
var client = new Client<Message>("127.0.0.1", 12345);
client.MessageReceived += async msg =>
{
Console.WriteLine($"Client received: {msg.Text}, Number={msg.Number}");
await client.SendAsync(new Message { Text = $"Got your {msg.Number}", Number = 999 });
};
await client.ConnectAsync();
await client.SendAsync(new Message { Text = "Hello Server", Number = 123 });
// Send nested objects and big collections through server
await client.SendAsync(new Message { Text = $"Nested test: {copy3[0].Name}", Number = copy3.Count });
await client.SendAsync(new Message { Text = $"Big list last value: {copy1[^1]}", Number = copy1.Count });
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
public class Address
{
public string Street { get; set; } = "";
public string City { get; set; } = "";
}
public class User
{
public int Id { get; set; }
public string Name { get; set; } = "";
public bool IsAdmin { get; set; }
public Address Home { get; set; } = new Address();
}
public class Message
{
public string Text { get; set; } = "";
public int Number { get; set; }
}
```

BIN
icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB