Initial version

This commit is contained in:
2025-11-21 21:04:44 +01:00
parent 4a6e3ae539
commit d1ce79dfae
30 changed files with 3209 additions and 126 deletions

93
.gitignore vendored
View File

@@ -2,7 +2,7 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
@@ -14,9 +14,6 @@
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
@@ -24,14 +21,10 @@ mono_crash.*
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
@@ -45,10 +38,9 @@ Generated\ Files/
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
# NUNIT
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
@@ -63,9 +55,6 @@ project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
@@ -83,8 +72,6 @@ StyleCopReport.xml
*.pgc
*.pgd
*.rsp
# but not Directory.Build.rsp, as it configures directory-level build defaults
!Directory.Build.rsp
*.sbr
*.tlb
*.tli
@@ -93,7 +80,6 @@ StyleCopReport.xml
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
@@ -135,6 +121,9 @@ _ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
@@ -145,11 +134,6 @@ _TeamCity*
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
@@ -197,8 +181,6 @@ PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
@@ -223,14 +205,12 @@ BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
!*.[Cc]ache/
# Others
ClientBin/
@@ -274,9 +254,6 @@ ServiceFabricBackup/
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
@@ -297,17 +274,6 @@ node_modules/
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
@@ -323,6 +289,10 @@ paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush personal settings
.cr/personal
@@ -364,53 +334,10 @@ ASALocalRun/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix

View File

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

View File

@@ -0,0 +1,81 @@
using EonaCat.Transfer;
using EonaCat.Transfer.Models;
NetworkConfig networkConfig = new NetworkConfig()
{
Protocol = ProtocolType.TCP,
Framing = FramingMode.Delimiter,
Delimiter = new byte[] { 0x0A }, // LF
EnableKeepAlive = true,
KeepAliveIntervalMs = 15000,
KeepAliveTimeoutMs = 5000,
AutoReconnect = true,
ReconnectDelayMs = 3000,
};
var server = new TcpServer(networkConfig);
server.ClientConnected += Server_ClientConnected;
server.ClientDisconnected += Server_ClientDisconnected;
server.MessageReceived += Server_MessageReceived;
void Server_MessageReceived(object? sender, (ClientConnection Client, NetworkMessage Message) e)
{
string message = System.Text.Encoding.UTF8.GetString(e.Message.Payload);
Console.WriteLine($"Received from {e.Client.Id}: {message}");
// Echo the message back to the client
var responseMessage = new NetworkMessage();
responseMessage.Payload = System.Text.Encoding.UTF8.GetBytes($"Echo: {message}");
server.SendMessageAsync(e.Client, responseMessage);
}
void Server_ClientDisconnected(object? sender, ClientConnection e)
{
Console.WriteLine($"{e.Id} disconnected {e.RemoteEndPoint.ToString()}");
}
void Server_ClientConnected(object? sender, ClientConnection e)
{
Console.WriteLine($"{e.Id} connected {e.RemoteEndPoint.ToString()}");
}
var client = new TcpClient(networkConfig);
client.Connected += Client_Connected;
client.MessageReceived += Client_MessageReceived;
client.Disconnected += Client_Disconnected;
void Client_Disconnected(object? sender, EventArgs e)
{
Console.WriteLine("Client disconnected from server");
}
void Client_MessageReceived(object? sender, NetworkMessage e)
{
string message = System.Text.Encoding.UTF8.GetString(e.Payload);
Console.WriteLine($"Received from server: {message}");
}
void Client_Connected(object? sender, EventArgs e)
{
Console.WriteLine("Client connected to server");
// Send a test message to the server
var message = new NetworkMessage();
message.Payload = System.Text.Encoding.UTF8.GetBytes("Hello, Server!");
client.SendMessageAsync(message);
}
await server.StartAsync(9000);
await client.ConnectAsync("127.0.0.1", 9000);
// Generate traffic
for (int i = 0; i < 10000; i++)
{
var message = new NetworkMessage();
message.Payload = System.Text.Encoding.UTF8.GetBytes($"Message {i + 1} from client");
await client.SendMessageAsync(message);
await Task.Delay(100);
}
Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();

7
EonaCat.Transfer.slnx Normal file
View File

@@ -0,0 +1,7 @@
<Solution>
<Folder Name="/Solution Items/">
<File Path="Readme.md" />
</Folder>
<Project Path="EonaCat.Transfer.Example/EonaCat.Transfer.Example.csproj" />
<Project Path="EonaCat.Transfer/EonaCat.Transfer.csproj" />
</Solution>

View File

@@ -0,0 +1,9 @@
namespace EonaCat.Transfer
{
public enum AesKeySize
{
Aes128 = 128,
Aes192 = 192,
Aes256 = 256
}
}

View File

@@ -0,0 +1,9 @@
namespace EonaCat.Transfer
{
public enum CompressionType
{
None,
GZip,
Deflate
}
}

View File

@@ -0,0 +1,49 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net48;net6.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<AssemblyTitle>EonaCat.Transfer</AssemblyTitle>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<PackageId>EonaCat.Transfer</PackageId>
<Title>EonaCat.Transfer</Title>
<Version>1.0.0</Version>
<Authors>EonaCat (Jeroen Saey)</Authors>
<Company>EonaCat (Jeroen Saey)</Company>
<Product>EonaCat.Transfer</Product>
<Description>Yet another .NET networking library.</Description>
<Copyright>EonaCat (Jeroen Saey)</Copyright>
<PackageProjectUrl>https://git.saey.me/EonaCat/EonaCat.Transfer</PackageProjectUrl>
<PackageIcon>icon.png</PackageIcon>
<PackageReadmeFile>Readme.md</PackageReadmeFile>
<RepositoryUrl>https://git.saey.me/EonaCat/EonaCat.Transfer</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageTags>Socket, TCP, UDP, REST, AES, Compression</PackageTags>
<PackageReleaseNotes>Yet another .NET networking library.</PackageReleaseNotes>
<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>
<ItemGroup>
<PackageReference Include="EonaCat.Json" Version="1.2.0" />
<PackageReference Include="System.Buffers" Version="4.6.1" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,10 @@
namespace EonaCat.Transfer
{
public enum FramingMode
{
None,
LengthPrefix,
Delimiter,
FixedLength
}
}

View File

@@ -0,0 +1,230 @@
using EonaCat.Transfer.Models;
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EonaCat.Transfer.Helpers
{
public static class AesHelper
{
/// <summary>
/// Generates a cryptographically secure random AES configuration
/// </summary>
public static AesConfig GenerateSecureConfig(AesKeySize keySize = AesKeySize.Aes256)
{
return AesEncryptionProvider.GenerateConfig(keySize);
}
/// <summary>
/// Creates AES configuration from a shared secret using PBKDF2
/// </summary>
public static AesConfig CreateFromSharedSecret(string secret, AesKeySize keySize = AesKeySize.Aes256)
{
return AesEncryptionProvider.FromSharedSecret(secret, keySize);
}
/// <summary>
/// Exports AES configuration to base64 strings for easy sharing/storage
/// </summary>
public static (string Key, string IV) ExportConfig(AesConfig config)
{
if (config.Key == null || config.IV == null)
{
throw new InvalidOperationException("AES config must have Key and IV to export");
}
return (Convert.ToBase64String(config.Key), Convert.ToBase64String(config.IV));
}
/// <summary>
/// Imports AES configuration from base64 strings
/// </summary>
public static AesConfig ImportConfig(string keyBase64, string ivBase64, AesKeySize keySize = AesKeySize.Aes256)
{
return new AesConfig
{
IsAesEnabled = true,
Key = Convert.FromBase64String(keyBase64),
IV = Convert.FromBase64String(ivBase64),
KeySize = keySize
};
}
/// <summary>
/// Saves AES configuration to a file (encrypted with password)
/// </summary>
public static void SaveConfigToFile(AesConfig config, string filePath, string password)
{
var keyIv = $"{Convert.ToBase64String(config.Key)}|{Convert.ToBase64String(config.IV)}";
var keyIvBytes = Encoding.UTF8.GetBytes(keyIv);
// Encrypt with password
using (var aes = Aes.Create())
{
var salt = new byte[16];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
#if NET6_0_OR_GREATER
using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, 100000, HashAlgorithmName.SHA256))
#else
using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, 100000))
#endif
{
aes.Key = deriveBytes.GetBytes(32);
aes.IV = deriveBytes.GetBytes(16);
}
using (var encryptor = aes.CreateEncryptor())
using (var ms = new MemoryStream())
{
ms.Write(salt, 0, salt.Length);
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(keyIvBytes, 0, keyIvBytes.Length);
}
File.WriteAllBytes(filePath, ms.ToArray());
}
}
}
/// <summary>
/// Loads AES configuration from a file (decrypted with password)
/// </summary>
public static AesConfig LoadConfigFromFile(string filePath, string password, AesKeySize keySize = AesKeySize.Aes256)
{
var fileBytes = File.ReadAllBytes(filePath);
var salt = new byte[16];
Array.Copy(fileBytes, salt, 16);
using (var aes = Aes.Create())
{
#if NET6_0_OR_GREATER
using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, 100000, HashAlgorithmName.SHA256))
#else
using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, 100000))
#endif
{
aes.Key = deriveBytes.GetBytes(32);
aes.IV = deriveBytes.GetBytes(16);
}
using (var decryptor = aes.CreateDecryptor())
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
{
cs.Write(fileBytes, 16, fileBytes.Length - 16);
}
var keyIv = Encoding.UTF8.GetString(ms.ToArray()).Split('|');
return ImportConfig(keyIv[0], keyIv[1], keySize);
}
}
}
/// <summary>
/// Performs a secure key exchange simulation (for demonstration - use real key exchange in production)
/// </summary>
public static (AesConfig ServerConfig, AesConfig ClientConfig) SimulateKeyExchange(string sharedSecret)
{
var config = CreateFromSharedSecret(sharedSecret);
return (
new AesConfig
{
IsAesEnabled = true,
Key = config.Key,
IV = config.IV,
KeySize = config.KeySize
},
new AesConfig
{
IsAesEnabled = true,
Key = config.Key,
IV = config.IV,
KeySize = config.KeySize
}
);
}
/// <summary>
/// Encrypts a single byte array (standalone utility)
/// </summary>
public static byte[] EncryptBytes(byte[] data, AesConfig config)
{
using (var provider = new AesEncryptionProvider(config))
{
return provider.Encrypt(data);
}
}
/// <summary>
/// Decrypts a single byte array (standalone utility)
/// </summary>
public static byte[] DecryptBytes(byte[] encryptedData, AesConfig config)
{
using (var provider = new AesEncryptionProvider(config))
{
return provider.Decrypt(encryptedData);
}
}
/// <summary>
/// Encrypts a string
/// </summary>
public static string EncryptString(string plainText, AesConfig config)
{
var plainBytes = Encoding.UTF8.GetBytes(plainText);
var encryptedBytes = EncryptBytes(plainBytes, config);
return Convert.ToBase64String(encryptedBytes);
}
/// <summary>
/// Decrypts a string
/// </summary>
public static string DecryptString(string encryptedText, AesConfig config)
{
var encryptedBytes = Convert.FromBase64String(encryptedText);
var plainBytes = DecryptBytes(encryptedBytes, config);
return Encoding.UTF8.GetString(plainBytes);
}
/// <summary>
/// Generates a cryptographically secure random password
/// </summary>
public static string GenerateSecurePassword(int length = 32)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
var result = new char[length];
var randomBytes = new byte[length];
using (var randomGenerator = RandomNumberGenerator.Create())
{
randomGenerator.GetBytes(randomBytes);
}
for (int i = 0; i < length; i++)
{
result[i] = chars[randomBytes[i] % chars.Length];
}
return new string(result);
}
}
}

View File

@@ -0,0 +1,60 @@
namespace EonaCat.Transfer.Helpers
{
public static class CompressionHelper
{
public static byte[] Compress(byte[] data, CompressionType type)
{
if (type == CompressionType.None || data == null || data.Length == 0)
{
return data;
}
using (var output = new MemoryStream())
{
Stream compressionStream = type == CompressionType.GZip
? (Stream)new System.IO.Compression.GZipStream(output, System.IO.Compression.CompressionMode.Compress)
: new System.IO.Compression.DeflateStream(output, System.IO.Compression.CompressionMode.Compress);
using (compressionStream)
{
compressionStream.Write(data, 0, data.Length);
}
return output.ToArray();
}
}
public static byte[] Decompress(byte[] data, CompressionType type)
{
if (type == CompressionType.None || data == null || data.Length == 0)
{
return data;
}
using (var input = new MemoryStream(data))
using (var output = new MemoryStream())
{
Stream decompressionStream = type == CompressionType.GZip
? (Stream)new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress)
: new System.IO.Compression.DeflateStream(input, System.IO.Compression.CompressionMode.Decompress);
using (decompressionStream)
{
decompressionStream.CopyTo(output);
}
return output.ToArray();
}
}
public static async Task<byte[]> CompressAsync(byte[] data, CompressionType type)
{
return await Task.Run(() => Compress(data, type));
}
public static async Task<byte[]> DecompressAsync(byte[] data, CompressionType type)
{
return await Task.Run(() => Decompress(data, type));
}
}
}

View File

@@ -0,0 +1,112 @@
using System.Net;
using System.Net.Sockets;
namespace EonaCat.Transfer.Helpers
{
public static class NetworkHelper
{
/// <summary>
/// Gets the local IP address
/// </summary>
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1";
}
/// <summary>
/// Checks if a port is available
/// </summary>
public static bool IsPortAvailable(int port)
{
try
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp))
{
socket.Bind(new IPEndPoint(IPAddress.Any, port));
return true;
}
}
catch
{
return false;
}
}
/// <summary>
/// Finds an available port in the specified range
/// </summary>
public static int FindAvailablePort(int startPort = 5000, int endPort = 65535)
{
for (int port = startPort; port <= endPort; port++)
{
if (IsPortAvailable(port))
{
return port;
}
}
throw new InvalidOperationException("No available ports found in the specified range");
}
/// <summary>
/// Validates an IP address
/// </summary>
public static bool IsValidIPAddress(string ipAddress)
{
return IPAddress.TryParse(ipAddress, out _);
}
/// <summary>
/// Performs a TCP ping (connection test)
/// </summary>
public static async Task<bool> TcpPingAsync(string host, int port, int timeoutMs = 5000)
{
try
{
using (var client = new System.Net.Sockets.TcpClient())
{
var connectTask = client.ConnectAsync(host, port);
var timeoutTask = Task.Delay(timeoutMs);
var completedTask = await Task.WhenAny(connectTask, timeoutTask);
return completedTask == connectTask && client.Connected;
}
}
catch
{
return false;
}
}
/// <summary>
/// Gets network latency to a host
/// </summary>
public static async Task<long> GetLatencyAsync(string host, int port, int attempts = 3)
{
var latencies = new List<long>();
for (int i = 0; i < attempts; i++)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var success = await TcpPingAsync(host, port);
sw.Stop();
if (success)
{
latencies.Add(sw.ElapsedMilliseconds);
}
await Task.Delay(100);
}
return latencies.Any() ? (long)latencies.Average() : -1;
}
}
}

View File

@@ -0,0 +1,17 @@
namespace EonaCat.Transfer
{
public enum MessageType : byte
{
Data = 0,
KeepAlive = 1,
KeepAliveResponse = 2,
FileTransferStart = 3,
FileTransferChunk = 4,
FileTransferEnd = 5,
Disconnect = 6,
Acknowledgment = 7,
Error = 8,
Handshake = 9,
HandshakeResponse = 10
}
}

View File

@@ -0,0 +1,15 @@
using System.Security.Cryptography;
namespace EonaCat.Transfer.Models
{
public class AesConfig
{
public bool IsAesEnabled { get; set; } = false;
public byte[] Key { get; set; }
public byte[] IV { get; set; }
public AesKeySize KeySize { get; set; } = AesKeySize.Aes256;
public CipherMode Mode { get; set; } = CipherMode.CBC;
public PaddingMode Padding { get; set; } = PaddingMode.PKCS7;
public string SharedSecret { get; set; } // For key derivation
}
}

View File

@@ -0,0 +1,147 @@
using System.Security.Cryptography;
using System.Text;
namespace EonaCat.Transfer.Models
{
public class AesEncryptionProvider : IDisposable
{
private readonly string _salt = "EonaCat_Transfer_Salt";
private readonly Aes _aes;
private readonly ICryptoTransform _encryptor;
private readonly ICryptoTransform _decryptor;
private bool _disposed;
public byte[] Key => _aes.Key;
public byte[] IV => _aes.IV;
public AesEncryptionProvider(AesConfig config, string salt = "EonaCat_Transfer_Salt")
{
_salt = salt;
_aes = Aes.Create();
_aes.KeySize = (int)config.KeySize;
_aes.Mode = config.Mode;
_aes.Padding = config.Padding;
if (config.Key != null && config.IV != null)
{
_aes.Key = config.Key;
_aes.IV = config.IV;
}
else if (!string.IsNullOrEmpty(config.SharedSecret))
{
// Derive key from shared secret using PBKDF2
DeriveKeyFromSecret(config.SharedSecret, config.KeySize);
}
else
{
// Generate random key and IV
_aes.GenerateKey();
_aes.GenerateIV();
}
_encryptor = _aes.CreateEncryptor();
_decryptor = _aes.CreateDecryptor();
}
private void DeriveKeyFromSecret(string secret, AesKeySize keySize)
{
// Use PBKDF2 for key derivation
var salt = Encoding.UTF8.GetBytes(_salt);
#if NET6_0_OR_GREATER
using (var deriveBytes = new Rfc2898DeriveBytes(
secret,
salt,
100000,
HashAlgorithmName.SHA256))
#else
using (var deriveBytes = new Rfc2898DeriveBytes(secret, salt, 100000))
#endif
{
_aes.Key = deriveBytes.GetBytes((int)keySize / 8);
_aes.IV = deriveBytes.GetBytes(16); // AES block size is always 128 bits (16 bytes)
}
}
public byte[] Encrypt(byte[] data)
{
if (data == null || data.Length == 0)
{
return data;
}
using (var ms = new MemoryStream())
using (var cs = new CryptoStream(ms, _encryptor, CryptoStreamMode.Write))
{
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
public byte[] Decrypt(byte[] encryptedData)
{
if (encryptedData == null || encryptedData.Length == 0)
{
return encryptedData;
}
using (var ms = new MemoryStream())
using (var cs = new CryptoStream(ms, _decryptor, CryptoStreamMode.Write))
{
cs.Write(encryptedData, 0, encryptedData.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
public async Task<byte[]> EncryptAsync(byte[] data)
{
return await Task.Run(() => Encrypt(data));
}
public async Task<byte[]> DecryptAsync(byte[] encryptedData)
{
return await Task.Run(() => Decrypt(encryptedData));
}
public static AesConfig GenerateConfig(AesKeySize keySize = AesKeySize.Aes256)
{
using (var aes = Aes.Create())
{
aes.KeySize = (int)keySize;
aes.GenerateKey();
aes.GenerateIV();
return new AesConfig
{
IsAesEnabled = true,
KeySize = keySize,
Key = aes.Key,
IV = aes.IV
};
}
}
public static AesConfig FromSharedSecret(string secret, AesKeySize keySize = AesKeySize.Aes256)
{
return new AesConfig
{
IsAesEnabled = true,
SharedSecret = secret,
KeySize = keySize
};
}
public void Dispose()
{
if (!_disposed)
{
_encryptor?.Dispose();
_decryptor?.Dispose();
_aes?.Dispose();
_disposed = true;
}
}
}
}

View File

@@ -0,0 +1,44 @@
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
namespace EonaCat.Transfer.Models
{
public class ClientConnection : IDisposable
{
public string Id { get; }
public EndPoint RemoteEndPoint { get; }
public DateTime ConnectedAt { get; }
public DateTime LastActivity { get; set; }
public long BytesSent { get; set; }
public long BytesReceived { get; set; }
public bool IsConnected { get; set; }
public ConcurrentDictionary<string, object> Metadata { get; }
internal Socket Socket { get; set; }
internal Stream Stream { get; set; }
internal CancellationTokenSource CancellationToken { get; set; }
internal ConcurrentDictionary<long, TaskCompletionSource<bool>> PendingAcknowledgments { get; }
public ClientConnection(Socket socket)
{
Id = Guid.NewGuid().ToString();
Socket = socket;
RemoteEndPoint = socket.RemoteEndPoint;
ConnectedAt = DateTime.UtcNow;
LastActivity = DateTime.UtcNow;
IsConnected = true;
CancellationToken = new CancellationTokenSource();
Metadata = new ConcurrentDictionary<string, object>();
PendingAcknowledgments = new ConcurrentDictionary<long, TaskCompletionSource<bool>>();
}
public void Dispose()
{
IsConnected = false;
CancellationToken?.Cancel();
Stream?.Dispose();
Socket?.Dispose();
}
}
}

View File

@@ -0,0 +1,52 @@
using System.Text;
namespace EonaCat.Transfer.Models
{
public class MessageBuilder
{
private readonly NetworkMessage _message;
public MessageBuilder()
{
_message = new NetworkMessage
{
Timestamp = DateTime.UtcNow
};
}
public MessageBuilder WithType(MessageType type)
{
_message.Type = type;
return this;
}
public MessageBuilder WithPayload(byte[] payload)
{
_message.Payload = payload;
return this;
}
public MessageBuilder WithPayload(string text)
{
_message.Payload = Encoding.UTF8.GetBytes(text);
return this;
}
public MessageBuilder WithSessionId(string sessionId)
{
_message.SessionId = sessionId;
return this;
}
public MessageBuilder WithSequenceNumber(long sequenceNumber)
{
_message.SequenceNumber = sequenceNumber;
return this;
}
public NetworkMessage Build()
{
return _message;
}
}
}

View File

@@ -0,0 +1,38 @@
namespace EonaCat.Transfer.Models
{
public class NetworkConfig
{
public ProtocolType Protocol { get; set; } = ProtocolType.TCP;
public FramingMode Framing { get; set; } = FramingMode.LengthPrefix;
public byte[] Delimiter { get; set; } = new byte[] { 0x0D, 0x0A }; // CRLF
public int FixedLength { get; set; } = 1024;
public bool AutoReconnect { get; set; } = true;
public int ReconnectDelayMs { get; set; } = 5000;
public int MaxReconnectAttempts { get; set; } = -1; // -1 = infinite
public bool EnableKeepAlive { get; set; } = true;
public int KeepAliveIntervalMs { get; set; } = 30000;
public int KeepAliveTimeoutMs { get; set; } = 10000;
public bool EnableNatPunchthrough { get; set; } = true;
public int BufferSize { get; set; } = 8192;
public int MaxConnections { get; set; } = 1000000;
public CompressionType Compression { get; set; } = CompressionType.None;
public bool EnableSsl { get; set; } = false;
public string SslCertificatePath { get; set; }
public string SslCertificatePassword { get; set; }
public System.Security.Cryptography.X509Certificates.X509Certificate2 SslCertificate { get; set; }
public bool SslValidateServerCertificate { get; set; } = true;
public string SslTargetHost { get; set; }
public System.Security.Authentication.SslProtocols SslProtocols { get; set; } =
System.Security.Authentication.SslProtocols.Tls12 |
System.Security.Authentication.SslProtocols.Tls13;
public AesConfig AesEncryption { get; set; } = new AesConfig();
public int SendTimeoutMs { get; set; } = 30000;
public int ReceiveTimeoutMs { get; set; } = 30000;
public bool NoDelay { get; set; } = true; // TCP_NODELAY
public int MaxMessageSize { get; set; } = 10 * 1024 * 1024; // 10MB
public int FileTransferChunkSize { get; set; } = 64 * 1024; // 64KB chunks
public string FileTransferDirectory { get; set; } = null; // null = temp directory
public bool IsMessageAcknowledgmentEnabled { get; set; } = false;
public int AcknowledgmentTimeoutMs { get; set; } = 5000;
}
}

View File

@@ -0,0 +1,46 @@
namespace EonaCat.Transfer.Models
{
public class NetworkMessage
{
public MessageType Type { get; set; }
public byte[] Payload { get; set; }
public string SessionId { get; set; }
public DateTime Timestamp { get; set; }
public long SequenceNumber { get; set; }
public static byte[] Serialize(NetworkMessage msg)
{
using (var messageStream = new MemoryStream())
using (var binaryWriter = new BinaryWriter(messageStream))
{
binaryWriter.Write((byte)msg.Type);
binaryWriter.Write(msg.SequenceNumber);
binaryWriter.Write(msg.Timestamp.ToBinary());
binaryWriter.Write(msg.SessionId ?? string.Empty);
binaryWriter.Write(msg.Payload?.Length ?? 0);
if (msg.Payload != null)
{
binaryWriter.Write(msg.Payload);
}
return messageStream.ToArray();
}
}
public static NetworkMessage Deserialize(byte[] data)
{
using (var memoryStream = new MemoryStream(data))
using (var binaryReader = new BinaryReader(memoryStream))
{
return new NetworkMessage
{
Type = (MessageType)binaryReader.ReadByte(),
SequenceNumber = binaryReader.ReadInt64(),
Timestamp = DateTime.FromBinary(binaryReader.ReadInt64()),
SessionId = binaryReader.ReadString(),
Payload = binaryReader.ReadBytes(binaryReader.ReadInt32())
};
}
}
}
}

View File

@@ -0,0 +1,67 @@
using System.Collections.Concurrent;
using System.Text;
namespace EonaCat.Transfer.Models
{
public class NetworkStatistics
{
public long TotalBytesSent { get; set; }
public long TotalBytesReceived { get; set; }
public long TotalMessagesSent { get; set; }
public long TotalMessagesReceived { get; set; }
public int ActiveConnections { get; set; }
public DateTime StartTime { get; set; }
public TimeSpan Uptime => DateTime.UtcNow - StartTime;
public double BytesSentPerSecond => TotalBytesSent / Uptime.TotalSeconds;
public double BytesReceivedPerSecond => TotalBytesReceived / Uptime.TotalSeconds;
public double MessagesSentPerSecond => TotalMessagesSent / Uptime.TotalSeconds;
public double MessagesReceivedPerSecond => TotalMessagesReceived / Uptime.TotalSeconds;
public ConcurrentDictionary<string, long> CustomCounters { get; } = new ConcurrentDictionary<string, long>();
public NetworkStatistics()
{
StartTime = DateTime.UtcNow;
}
public void IncrementCounter(string name, long value = 1)
{
CustomCounters.AddOrUpdate(name, value, (key, oldValue) => oldValue + value);
}
public override string ToString()
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine($"Network Statistics (Uptime: {Uptime:hh\\:mm\\:ss})");
stringBuilder.AppendLine($"Active Connections: {ActiveConnections}");
stringBuilder.AppendLine($"Total Sent: {FormatBytes(TotalBytesSent)} ({TotalMessagesSent} messages)");
stringBuilder.AppendLine($"Total Received: {FormatBytes(TotalBytesReceived)} ({TotalMessagesReceived} messages)");
stringBuilder.AppendLine($"Send Rate: {FormatBytes((long)BytesSentPerSecond)}/s ({MessagesSentPerSecond:F2} msg/s)");
stringBuilder.AppendLine($"Receive Rate: {FormatBytes((long)BytesReceivedPerSecond)}/s ({MessagesReceivedPerSecond:F2} msg/s)");
if (CustomCounters.Any())
{
stringBuilder.AppendLine("Custom Counters:");
foreach (var kvp in CustomCounters)
{
stringBuilder.AppendLine($" {kvp.Key}: {kvp.Value}");
}
}
return stringBuilder.ToString();
}
private static string FormatBytes(long bytes)
{
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = bytes;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1)
{
order++;
len = len / 1024;
}
return $"{len:0.##} {sizes[order]}";
}
}
}

View File

@@ -0,0 +1,9 @@
namespace EonaCat.Transfer
{
public enum ProtocolType
{
TCP,
UDP,
REST
}
}

View File

@@ -0,0 +1,145 @@
using EonaCat.Json;
using EonaCat.Transfer.Models;
using System.Net.Http;
using System.Text;
namespace EonaCat.Transfer
{
public class RestClient : IDisposable
{
private readonly HttpClient _httpClient;
private readonly NetworkConfig _config;
public event EventHandler<(string Url, long BytesDownloaded, long? TotalBytes)> DownloadProgress;
public RestClient(NetworkConfig config = null)
{
_config = config ?? new NetworkConfig();
var handler = new HttpClientHandler();
if (_config.EnableSsl && !_config.SslValidateServerCertificate)
{
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
}
_httpClient = new HttpClient(handler)
{
Timeout = TimeSpan.FromMilliseconds(_config.SendTimeoutMs)
};
}
public void SetAuthorizationHeader(string scheme, string parameter)
{
_httpClient.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue(scheme, parameter);
}
public void SetBearerToken(string token)
{
SetAuthorizationHeader("Bearer", token);
}
public void AddHeader(string name, string value)
{
_httpClient.DefaultRequestHeaders.Add(name, value);
}
public async Task<string> GetAsync(string url)
{
var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public async Task<T> GetAsync<T>(string url)
{
var json = await GetAsync(url);
return JsonHelper.ToObject<T>(json);
}
public async Task<string> PostAsync(string url, string json)
{
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public async Task<TResponse> PostAsync<TRequest, TResponse>(string url, TRequest data)
{
var json = JsonHelper.ToJson(data);
var responseJson = await PostAsync(url, json);
return JsonHelper.ToObject<TResponse>(responseJson);
}
public async Task<string> PutAsync(string url, string json)
{
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PutAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public async Task<string> DeleteAsync(string url)
{
var response = await _httpClient.DeleteAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public async Task<byte[]> DownloadFileAsync(string url)
{
using (var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
var totalBytes = response.Content.Headers.ContentLength;
using (var stream = await response.Content.ReadAsStreamAsync())
using (var memoryStream = new MemoryStream())
{
var buffer = new byte[8192];
long downloadedBytes = 0;
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await memoryStream.WriteAsync(buffer, 0, bytesRead);
downloadedBytes += bytesRead;
DownloadProgress?.Invoke(this, (url, downloadedBytes, totalBytes));
}
return memoryStream.ToArray();
}
}
}
public async Task DownloadFileAsync(string url, string destinationPath)
{
using (var http = new HttpClient())
using (var stream = await http.GetStreamAsync(url))
using (var file = File.Create(destinationPath))
{
await stream.CopyToAsync(file);
}
}
public async Task<string> UploadFileAsync(string url, string filePath, string fieldName = "file")
{
using (var form = new MultipartFormDataContent())
using (var fileStream = File.OpenRead(filePath))
{
var fileContent = new StreamContent(fileStream);
form.Add(fileContent, fieldName, Path.GetFileName(filePath));
var response = await _httpClient.PostAsync(url, form);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
}

View File

@@ -0,0 +1,153 @@
using System.Security.Cryptography.X509Certificates;
namespace EonaCat.Transfer.Helpers
{
public static class SslHelper
{
/// <summary>
/// Creates a self-signed certificate for testing purposes
/// </summary>
public static X509Certificate2 CreateSelfSignedCertificate(string subjectName, int validityYears = 5)
{
#if NET6_0_OR_GREATER
using (var rsa = System.Security.Cryptography.RSA.Create(2048))
{
var request = new System.Security.Cryptography.X509Certificates.CertificateRequest(
$"CN={subjectName}",
rsa,
System.Security.Cryptography.HashAlgorithmName.SHA256,
System.Security.Cryptography.RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(
new System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension(
false, false, 0, true));
request.CertificateExtensions.Add(
new System.Security.Cryptography.X509Certificates.X509KeyUsageExtension(
System.Security.Cryptography.X509Certificates.X509KeyUsageFlags.DigitalSignature |
System.Security.Cryptography.X509Certificates.X509KeyUsageFlags.KeyEncipherment,
true));
request.CertificateExtensions.Add(
new System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension(
new System.Security.Cryptography.OidCollection
{
new System.Security.Cryptography.Oid("1.3.6.1.5.5.7.3.1") // Server Authentication
},
true));
var sanBuilder = new System.Security.Cryptography.X509Certificates.SubjectAlternativeNameBuilder();
sanBuilder.AddDnsName(subjectName);
sanBuilder.AddDnsName("localhost");
sanBuilder.AddIpAddress(System.Net.IPAddress.Loopback);
request.CertificateExtensions.Add(sanBuilder.Build());
var notBefore = DateTimeOffset.UtcNow.AddDays(-1);
var notAfter = DateTimeOffset.UtcNow.AddYears(validityYears);
var certificate = request.CreateSelfSigned(notBefore, notAfter);
return new X509Certificate2(
certificate.Export(X509ContentType.Pfx, "temp"),
"temp",
X509KeyStorageFlags.Exportable);
}
#else
throw new NotSupportedException("Self-signed certificate generation requires .NET 6.0 or higher. " +
"For .NET Framework 4.8, use makecert.exe or PowerShell New-SelfSignedCertificate.");
#endif
}
/// <summary>
/// Loads certificate from file
/// </summary>
public static X509Certificate2 LoadCertificate(string path, string password = null)
{
return new X509Certificate2(path, password);
}
/// <summary>
/// Saves certificate to file
/// </summary>
public static void SaveCertificate(X509Certificate2 certificate, string path, string password)
{
var bytes = certificate.Export(X509ContentType.Pfx, password);
File.WriteAllBytes(path, bytes);
}
/// <summary>
/// Gets certificate from Windows certificate store
/// </summary>
public static X509Certificate2 GetCertificateFromStore(
string subjectName,
StoreName storeName = StoreName.My,
StoreLocation storeLocation = StoreLocation.CurrentUser)
{
using (var store = new X509Store(storeName, storeLocation))
{
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates.Find(
X509FindType.FindBySubjectName,
subjectName,
validOnly: false);
return certificates.Count > 0 ? certificates[0] : null;
}
}
/// <summary>
/// Installs certificate to Windows certificate store
/// </summary>
public static void InstallCertificateToStore(
X509Certificate2 certificate,
StoreName storeName = StoreName.My,
StoreLocation storeLocation = StoreLocation.CurrentUser)
{
using (var store = new X509Store(storeName, storeLocation))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certificate);
}
}
/// <summary>
/// Validates if certificate is valid for the given hostname
/// </summary>
public static bool ValidateCertificateForHost(X509Certificate2 certificate, string hostname)
{
if (certificate == null)
{
return false;
}
// Check expiration
if (DateTime.Now < certificate.NotBefore || DateTime.Now > certificate.NotAfter)
{
return false;
}
// Check subject name
var subject = certificate.Subject;
if (subject.Contains($"CN={hostname}"))
{
return true;
}
// Check SAN (Subject Alternative Names)
foreach (var extension in certificate.Extensions)
{
if (extension.Oid.Value == "2.5.29.17") // SAN OID
{
var asnData = new System.Security.Cryptography.AsnEncodedData(extension.Oid, extension.RawData);
var sanString = asnData.Format(false);
if (sanString.Contains(hostname))
{
return true;
}
}
}
return false;
}
}
}

View File

@@ -0,0 +1,575 @@
using EonaCat.Transfer.Models;
using System.Buffers;
using System.Collections.Concurrent;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace EonaCat.Transfer
{
public class TcpClient : IDisposable
{
private readonly NetworkConfig _config;
private Socket _socket;
private Stream _stream;
private CancellationTokenSource _cts;
private long _sequenceNumber;
private Task _receiveTask;
private Task _keepAliveTask;
private int _reconnectAttempts;
private AesEncryptionProvider _aesProvider;
private string _lastHost;
private int _lastPort;
private readonly ConcurrentDictionary<long, TaskCompletionSource<bool>> _pendingAcknowledgments;
private readonly ConcurrentDictionary<string, FileTransferState> _activeFileTransfers;
public bool IsConnected => _socket?.Connected ?? false;
public long BytesSent { get; private set; }
public long BytesReceived { get; private set; }
public DateTime LastActivity { get; private set; }
public int ReconnectAttempts => _reconnectAttempts;
public event EventHandler Connected;
public event EventHandler Disconnected;
public event EventHandler<int> Reconnecting;
public event EventHandler<NetworkMessage> MessageReceived;
public event EventHandler<(string FilePath, long Size)> FileTransferStarted;
public event EventHandler<(string FilePath, long BytesTransferred, long TotalBytes)> FileTransferProgress;
public event EventHandler<string> FileTransferCompleted;
public event EventHandler<Exception> Error;
private class FileTransferState
{
public string FileName { get; set; }
public long TotalBytes { get; set; }
public long BytesReceived { get; set; }
public FileStream Stream { get; set; }
}
public TcpClient(NetworkConfig config = null)
{
_config = config ?? new NetworkConfig();
_pendingAcknowledgments = new ConcurrentDictionary<long, TaskCompletionSource<bool>>();
_activeFileTransfers = new ConcurrentDictionary<string, FileTransferState>();
if (_config.AesEncryption?.IsAesEnabled == true)
{
_aesProvider = new AesEncryptionProvider(_config.AesEncryption);
}
}
public async Task ConnectAsync(string host, int port)
{
_lastHost = host;
_lastPort = port;
_cts = new CancellationTokenSource();
await ConnectInternalAsync(host, port);
}
private async Task ConnectInternalAsync(string host, int port)
{
try
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
if (_config.NoDelay)
{
_socket.NoDelay = true;
}
_socket.SendTimeout = _config.SendTimeoutMs;
_socket.ReceiveTimeout = _config.ReceiveTimeoutMs;
await _socket.ConnectAsync(host, port);
Stream stream = new NetworkStream(_socket);
// Enable SSL/TLS if configured
if (_config.EnableSsl)
{
var sslStream = new SslStream(
stream,
false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
null);
var targetHost = _config.SslTargetHost ?? host;
await sslStream.AuthenticateAsClientAsync(
targetHost,
null,
_config.SslProtocols,
checkCertificateRevocation: true);
stream = sslStream;
}
_stream = stream;
LastActivity = DateTime.UtcNow;
_reconnectAttempts = 0;
Connected?.Invoke(this, EventArgs.Empty);
_receiveTask = Task.Run(() => ReceiveLoopAsync(_cts.Token));
if (_config.EnableKeepAlive)
{
_keepAliveTask = Task.Run(() => KeepAliveLoopAsync(_cts.Token));
}
}
catch (Exception ex)
{
Error?.Invoke(this, ex);
await HandleReconnectAsync(host, port);
}
}
private async Task HandleReconnectAsync(string host, int port)
{
if (_config.AutoReconnect &&
(_config.MaxReconnectAttempts == -1 || _reconnectAttempts < _config.MaxReconnectAttempts))
{
_reconnectAttempts++;
Reconnecting?.Invoke(this, _reconnectAttempts);
await Task.Delay(_config.ReconnectDelayMs);
if (!_cts.Token.IsCancellationRequested)
{
await ConnectInternalAsync(host, port);
}
}
}
private async Task ReceiveLoopAsync(CancellationToken ct)
{
var buffer = ArrayPool<byte>.Shared.Rent(_config.BufferSize);
try
{
while (!ct.IsCancellationRequested && IsConnected)
{
var message = await ReceiveMessageAsync(buffer, ct);
if (message == null)
{
break;
}
LastActivity = DateTime.UtcNow;
BytesReceived += message.Payload?.Length ?? 0;
switch (message.Type)
{
case MessageType.Data:
MessageReceived?.Invoke(this, message);
if (_config.IsMessageAcknowledgmentEnabled)
{
await SendMessageAsync(new NetworkMessage
{
Type = MessageType.Acknowledgment,
SequenceNumber = message.SequenceNumber
});
}
break;
case MessageType.KeepAliveResponse:
// Keep alive acknowledged
break;
case MessageType.FileTransferStart:
await HandleFileTransferStartAsync(message);
break;
case MessageType.FileTransferChunk:
await HandleFileTransferChunkAsync(message);
break;
case MessageType.FileTransferEnd:
await HandleFileTransferEndAsync(message);
break;
case MessageType.Acknowledgment:
if (_pendingAcknowledgments.TryRemove(message.SequenceNumber, out var tcs))
{
tcs.SetResult(true);
}
break;
}
}
}
catch (Exception ex)
{
Error?.Invoke(this, ex);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
await HandleDisconnectAsync();
}
}
private async Task<NetworkMessage> ReceiveMessageAsync(byte[] buffer, CancellationToken ct)
{
try
{
byte[] data = null;
switch (_config.Framing)
{
case FramingMode.LengthPrefix:
var lengthBytes = new byte[4];
await ReadExactAsync(_stream, lengthBytes, 0, 4, ct);
var length = BitConverter.ToInt32(lengthBytes, 0);
if (length > _config.MaxMessageSize || length < 0)
{
throw new InvalidDataException("Invalid message length");
}
data = new byte[length];
await ReadExactAsync(_stream, data, 0, length, ct);
break;
case FramingMode.Delimiter:
using (var ms = new MemoryStream())
{
var delimiterPos = 0;
while (true)
{
var b = _stream.ReadByte();
if (b == -1)
{
return null;
}
ms.WriteByte((byte)b);
if ((byte)b == _config.Delimiter[delimiterPos])
{
delimiterPos++;
if (delimiterPos == _config.Delimiter.Length)
{
data = ms.ToArray();
Array.Resize(ref data, data.Length - _config.Delimiter.Length);
break;
}
}
else
{
delimiterPos = 0;
}
if (ms.Length > _config.MaxMessageSize)
{
throw new InvalidDataException("Message too large");
}
}
}
break;
case FramingMode.FixedLength:
data = new byte[_config.FixedLength];
await ReadExactAsync(_stream, data, 0, _config.FixedLength, ct);
break;
case FramingMode.None:
var bytesRead = await _stream.ReadAsync(buffer, 0, buffer.Length, ct);
if (bytesRead == 0)
{
return null;
}
data = new byte[bytesRead];
Array.Copy(buffer, data, bytesRead);
break;
}
// Apply AES decryption if enabled
if (_aesProvider != null)
{
try
{
data = await _aesProvider.DecryptAsync(data);
}
catch
{
// If decryption fails, message might not be encrypted (keepalive, etc.)
}
}
return NetworkMessage.Deserialize(data);
}
catch (Exception)
{
return null;
}
}
private async Task ReadExactAsync(Stream stream, byte[] buffer, int offset, int count, CancellationToken ct)
{
var totalRead = 0;
while (totalRead < count)
{
var read = await stream.ReadAsync(buffer, offset + totalRead, count - totalRead, ct);
if (read == 0)
{
throw new EndOfStreamException();
}
totalRead += read;
}
}
private bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (!_config.SslValidateServerCertificate)
{
return true;
}
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
Error?.Invoke(this, new Exception($"SSL Certificate error: {sslPolicyErrors}"));
return false;
}
private async Task KeepAliveLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested && IsConnected)
{
try
{
await Task.Delay(_config.KeepAliveIntervalMs, ct);
await SendMessageAsync(new NetworkMessage { Type = MessageType.KeepAlive });
}
catch
{
break;
}
}
}
public async Task SendMessageAsync(NetworkMessage message)
{
if (!IsConnected)
{
return;
}
message.SequenceNumber = Interlocked.Increment(ref _sequenceNumber);
message.Timestamp = DateTime.UtcNow;
var data = NetworkMessage.Serialize(message);
// Apply AES encryption if enabled
if (_aesProvider != null && message.Type == MessageType.Data)
{
data = await _aesProvider.EncryptAsync(data);
}
// Apply framing
await SendFramedDataAsync(data, _cts.Token);
BytesSent += data.Length;
LastActivity = DateTime.UtcNow;
// Wait for acknowledgment if enabled
if (_config.IsMessageAcknowledgmentEnabled && message.Type == MessageType.Data)
{
var tcs = new TaskCompletionSource<bool>();
_pendingAcknowledgments[message.SequenceNumber] = tcs;
var ackTask = tcs.Task;
var timeoutTask = Task.Delay(_config.AcknowledgmentTimeoutMs);
if (await Task.WhenAny(ackTask, timeoutTask) == timeoutTask)
{
_pendingAcknowledgments.TryRemove(message.SequenceNumber, out _);
throw new TimeoutException("Message acknowledgment timeout");
}
}
}
private async Task SendFramedDataAsync(byte[] data, CancellationToken ct)
{
switch (_config.Framing)
{
case FramingMode.LengthPrefix:
var lengthBytes = BitConverter.GetBytes(data.Length);
await _stream.WriteAsync(lengthBytes, 0, lengthBytes.Length, ct);
await _stream.WriteAsync(data, 0, data.Length, ct);
break;
case FramingMode.Delimiter:
await _stream.WriteAsync(data, 0, data.Length, ct);
await _stream.WriteAsync(_config.Delimiter, 0, _config.Delimiter.Length, ct);
break;
case FramingMode.FixedLength:
case FramingMode.None:
await _stream.WriteAsync(data, 0, data.Length, ct);
break;
}
await _stream.FlushAsync(ct);
}
public async Task SendDataAsync(byte[] data) =>
await SendMessageAsync(new NetworkMessage { Type = MessageType.Data, Payload = data });
public async Task SendStringAsync(string text) =>
await SendDataAsync(Encoding.UTF8.GetBytes(text));
public async Task SendFileAsync(string filePath)
{
var fileInfo = new FileInfo(filePath);
if (!fileInfo.Exists)
{
throw new FileNotFoundException("File not found", filePath);
}
var fileName = fileInfo.Name;
var fileSize = fileInfo.Length;
// Send start message
var startPayload = Encoding.UTF8.GetBytes($"{fileName}|{fileSize}");
await SendMessageAsync(new NetworkMessage
{
Type = MessageType.FileTransferStart,
Payload = startPayload
});
// Send file chunks
using (var fs = File.OpenRead(filePath))
{
var buffer = new byte[_config.FileTransferChunkSize];
int bytesRead;
while ((bytesRead = await fs.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
var chunk = new byte[bytesRead];
Array.Copy(buffer, chunk, bytesRead);
await SendMessageAsync(new NetworkMessage
{
Type = MessageType.FileTransferChunk,
Payload = chunk
});
}
}
// Send end message
await SendMessageAsync(new NetworkMessage
{
Type = MessageType.FileTransferEnd,
Payload = Encoding.UTF8.GetBytes(fileName)
});
}
private async Task HandleFileTransferStartAsync(NetworkMessage message)
{
try
{
var info = Encoding.UTF8.GetString(message.Payload).Split('|');
var fileName = info[0];
var fileSize = long.Parse(info[1]);
var saveDirectory = _config.FileTransferDirectory ?? Path.GetTempPath();
if (!Directory.Exists(saveDirectory))
{
Directory.CreateDirectory(saveDirectory);
}
var savePath = Path.Combine(saveDirectory, fileName);
// Ensure unique filename
var counter = 1;
var nameWithoutExt = Path.GetFileNameWithoutExtension(fileName);
var extension = Path.GetExtension(fileName);
while (File.Exists(savePath))
{
savePath = Path.Combine(saveDirectory, $"{nameWithoutExt}_{counter}{extension}");
counter++;
}
var transferState = new FileTransferState
{
FileName = savePath,
TotalBytes = fileSize,
BytesReceived = 0,
Stream = File.Create(savePath)
};
_activeFileTransfers[fileName] = transferState;
FileTransferStarted?.Invoke(this, (savePath, fileSize));
}
catch (Exception ex)
{
Error?.Invoke(this, ex);
}
}
private async Task HandleFileTransferChunkAsync(NetworkMessage message)
{
// Find active transfer by matching the message
foreach (var kvp in _activeFileTransfers)
{
var transfer = kvp.Value;
await transfer.Stream.WriteAsync(message.Payload, 0, message.Payload.Length);
transfer.BytesReceived += message.Payload.Length;
FileTransferProgress?.Invoke(this, (transfer.FileName, transfer.BytesReceived, transfer.TotalBytes));
break; // Assuming one active transfer at a time
}
}
private async Task HandleFileTransferEndAsync(NetworkMessage message)
{
var fileName = Encoding.UTF8.GetString(message.Payload);
if (_activeFileTransfers.TryRemove(fileName, out var transfer))
{
transfer.Stream.Dispose();
FileTransferCompleted?.Invoke(this, transfer.FileName);
}
}
private async Task HandleDisconnectAsync()
{
Disconnected?.Invoke(this, EventArgs.Empty);
// Clean up file transfers
foreach (var transfer in _activeFileTransfers.Values)
{
transfer.Stream?.Dispose();
}
_activeFileTransfers.Clear();
if (_config.AutoReconnect && !_cts.Token.IsCancellationRequested && _lastHost != null)
{
await HandleReconnectAsync(_lastHost, _lastPort);
}
}
public void Disconnect()
{
_cts?.Cancel();
_stream?.Dispose();
_socket?.Dispose();
}
public void Dispose()
{
Disconnect();
_aesProvider?.Dispose();
foreach (var transfer in _activeFileTransfers.Values)
{
transfer.Stream?.Dispose();
}
_activeFileTransfers.Clear();
}
}
}

View File

@@ -0,0 +1,90 @@
using EonaCat.Transfer.Models;
using System.Collections.Concurrent;
namespace EonaCat.Transfer
{
public class TcpConnectionPool : IDisposable
{
private readonly NetworkConfig _config;
private readonly ConcurrentBag<TcpClient> _availableConnections;
private readonly ConcurrentDictionary<string, TcpClient> _activeConnections;
private readonly SemaphoreSlim _semaphore;
private readonly string _host;
private readonly int _port;
private int _totalCreated;
public int AvailableConnections => _availableConnections.Count;
public int ActiveConnections => _activeConnections.Count;
public int TotalCreated => _totalCreated;
public TcpConnectionPool(string host, int port, int maxConnections = 100, NetworkConfig config = null)
{
_host = host;
_port = port;
_config = config ?? new NetworkConfig();
_availableConnections = new ConcurrentBag<TcpClient>();
_activeConnections = new ConcurrentDictionary<string, TcpClient>();
_semaphore = new SemaphoreSlim(maxConnections);
}
public async Task<TcpClient> AcquireAsync()
{
await _semaphore.WaitAsync();
if (_availableConnections.TryTake(out var client))
{
if (client.IsConnected)
{
_activeConnections[Guid.NewGuid().ToString()] = client;
return client;
}
client.Dispose();
}
// Create new connection
var newClient = new TcpClient(_config);
await newClient.ConnectAsync(_host, _port);
Interlocked.Increment(ref _totalCreated);
var id = Guid.NewGuid().ToString();
_activeConnections[id] = newClient;
return newClient;
}
public void Release(TcpClient client)
{
var entry = _activeConnections.FirstOrDefault(kvp => kvp.Value == client);
if (entry.Key != null)
{
_activeConnections.TryRemove(entry.Key, out _);
if (client.IsConnected)
{
_availableConnections.Add(client);
}
else
{
client.Dispose();
}
_semaphore.Release();
}
}
public void Dispose()
{
while (_availableConnections.TryTake(out var client))
{
client.Dispose();
}
foreach (var client in _activeConnections.Values)
{
client.Dispose();
}
_activeConnections.Clear();
_semaphore?.Dispose();
}
}
}

View File

@@ -0,0 +1,546 @@
using EonaCat.Transfer.Models;
using System.Buffers;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace EonaCat.Transfer
{
public class TcpServer : IDisposable
{
private readonly NetworkConfig _config;
private Socket _listener;
private readonly ConcurrentDictionary<string, ClientConnection> _clients;
private CancellationTokenSource _cts;
private long _sequenceNumber;
private readonly SemaphoreSlim _connectionSemaphore;
private AesEncryptionProvider _aesProvider;
public event EventHandler<ClientConnection> ClientConnected;
public event EventHandler<ClientConnection> ClientDisconnected;
public event EventHandler<(ClientConnection Client, NetworkMessage Message)> MessageReceived;
public event EventHandler<(ClientConnection Client, string FilePath, long Size)> FileTransferStarted;
public event EventHandler<(ClientConnection Client, string FilePath)> FileTransferCompleted;
public event EventHandler<Exception> Error;
public int ActiveConnections => _clients.Count;
public TcpServer(NetworkConfig config = null)
{
_config = config ?? new NetworkConfig();
_clients = new ConcurrentDictionary<string, ClientConnection>();
_connectionSemaphore = new SemaphoreSlim(_config.MaxConnections);
if (_config.AesEncryption?.IsAesEnabled == true)
{
_aesProvider = new AesEncryptionProvider(_config.AesEncryption);
}
}
public async Task StartAsync(int port, string bindAddress = "0.0.0.0")
{
_cts = new CancellationTokenSource();
_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
if (_config.NoDelay)
{
_listener.NoDelay = true;
}
_listener.Bind(new IPEndPoint(IPAddress.Parse(bindAddress), port));
_listener.Listen(_config.MaxConnections);
_ = Task.Run(() => AcceptClientsAsync(_cts.Token));
}
private async Task AcceptClientsAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await _connectionSemaphore.WaitAsync(ct);
var socket = await _listener.AcceptAsync();
var client = new ClientConnection(socket);
if (_clients.TryAdd(client.Id, client))
{
ClientConnected?.Invoke(this, client);
_ = Task.Run(() => HandleClientAsync(client), ct);
if (_config.EnableKeepAlive)
{
_ = Task.Run(() => KeepAliveLoopAsync(client), ct);
}
}
}
catch (Exception ex)
{
_connectionSemaphore.Release();
if (!ct.IsCancellationRequested)
{
Error?.Invoke(this, ex);
}
}
}
}
private async Task HandleClientAsync(ClientConnection client)
{
var buffer = ArrayPool<byte>.Shared.Rent(_config.BufferSize);
try
{
Stream stream = new NetworkStream(client.Socket);
// Enable SSL/TLS if configured
if (_config.EnableSsl)
{
var sslStream = new SslStream(stream, false);
if (_config.SslCertificate == null && !string.IsNullOrEmpty(_config.SslCertificatePath))
{
_config.SslCertificate = new X509Certificate2(
_config.SslCertificatePath,
_config.SslCertificatePassword);
}
await sslStream.AuthenticateAsServerAsync(
_config.SslCertificate,
clientCertificateRequired: false,
_config.SslProtocols,
checkCertificateRevocation: true);
stream = sslStream;
}
client.Stream = stream;
while (client.IsConnected && !client.CancellationToken.Token.IsCancellationRequested)
{
var message = await ReceiveMessageAsync(stream, buffer, client.CancellationToken.Token);
if (message == null)
{
break;
}
client.LastActivity = DateTime.UtcNow;
client.BytesReceived += message.Payload?.Length ?? 0;
switch (message.Type)
{
case MessageType.Data:
MessageReceived?.Invoke(this, (client, message));
if (_config.IsMessageAcknowledgmentEnabled)
{
await SendMessageAsync(client, new NetworkMessage
{
Type = MessageType.Acknowledgment,
SequenceNumber = message.SequenceNumber
});
}
break;
case MessageType.KeepAlive:
await SendMessageAsync(client, new NetworkMessage
{
Type = MessageType.KeepAliveResponse
});
break;
case MessageType.FileTransferStart:
await HandleFileTransferAsync(client, message);
break;
case MessageType.Acknowledgment:
if (client.PendingAcknowledgments.TryRemove(message.SequenceNumber, out var tcs))
{
tcs.SetResult(true);
}
break;
case MessageType.Disconnect:
client.IsConnected = false;
break;
}
}
}
catch (Exception ex)
{
Error?.Invoke(this, ex);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
DisconnectClient(client);
}
}
private async Task<NetworkMessage> ReceiveMessageAsync(Stream stream, byte[] buffer, CancellationToken ct)
{
try
{
byte[] data = null;
switch (_config.Framing)
{
case FramingMode.LengthPrefix:
var lengthBytes = new byte[4];
await ReadExactAsync(stream, lengthBytes, 0, 4, ct);
var length = BitConverter.ToInt32(lengthBytes, 0);
if (length > _config.MaxMessageSize || length < 0)
{
throw new InvalidDataException("Invalid message length");
}
data = new byte[length];
await ReadExactAsync(stream, data, 0, length, ct);
break;
case FramingMode.Delimiter:
using (var ms = new MemoryStream())
{
var delimiterPos = 0;
while (true)
{
var b = stream.ReadByte();
if (b == -1)
{
return null;
}
ms.WriteByte((byte)b);
if ((byte)b == _config.Delimiter[delimiterPos])
{
delimiterPos++;
if (delimiterPos == _config.Delimiter.Length)
{
data = ms.ToArray();
Array.Resize(ref data, data.Length - _config.Delimiter.Length);
break;
}
}
else
{
delimiterPos = 0;
}
if (ms.Length > _config.MaxMessageSize)
{
throw new InvalidDataException("Message too large");
}
}
}
break;
case FramingMode.FixedLength:
data = new byte[_config.FixedLength];
await ReadExactAsync(stream, data, 0, _config.FixedLength, ct);
break;
case FramingMode.None:
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, ct);
if (bytesRead == 0)
{
return null;
}
data = new byte[bytesRead];
Array.Copy(buffer, data, bytesRead);
break;
}
// Apply AES decryption if enabled
if (_aesProvider != null)
{
try
{
data = await _aesProvider.DecryptAsync(data);
}
catch
{
// If decryption fails, it might be a non-data message (keepalive, etc.)
// Try to deserialize as-is
}
}
return NetworkMessage.Deserialize(data);
}
catch (Exception)
{
return null;
}
}
private async Task ReadExactAsync(Stream stream, byte[] buffer, int offset, int count, CancellationToken ct)
{
var totalRead = 0;
while (totalRead < count)
{
var read = await stream.ReadAsync(buffer, offset + totalRead, count - totalRead, ct);
if (read == 0)
{
throw new EndOfStreamException();
}
totalRead += read;
}
}
private async Task KeepAliveLoopAsync(ClientConnection client)
{
while (client.IsConnected && !client.CancellationToken.Token.IsCancellationRequested)
{
try
{
await Task.Delay(_config.KeepAliveIntervalMs, client.CancellationToken.Token);
if ((DateTime.UtcNow - client.LastActivity).TotalMilliseconds > _config.KeepAliveTimeoutMs)
{
client.IsConnected = false;
break;
}
await SendMessageAsync(client, new NetworkMessage
{
Type = MessageType.KeepAlive
});
}
catch
{
break;
}
}
}
public async Task SendMessageAsync(ClientConnection client, NetworkMessage message)
{
if (!client.IsConnected)
{
return;
}
try
{
message.SequenceNumber = Interlocked.Increment(ref _sequenceNumber);
message.Timestamp = DateTime.UtcNow;
var data = NetworkMessage.Serialize(message);
// Apply AES encryption if enabled
if (_aesProvider != null && message.Type == MessageType.Data)
{
data = await _aesProvider.EncryptAsync(data);
}
await SendFramedDataAsync(client.Stream, data, client.CancellationToken.Token);
client.BytesSent += data.Length;
client.LastActivity = DateTime.UtcNow;
// Wait for acknowledgment if enabled
if (_config.IsMessageAcknowledgmentEnabled && message.Type == MessageType.Data)
{
var tcs = new TaskCompletionSource<bool>();
client.PendingAcknowledgments[message.SequenceNumber] = tcs;
var ackTask = tcs.Task;
var timeoutTask = Task.Delay(_config.AcknowledgmentTimeoutMs);
if (await Task.WhenAny(ackTask, timeoutTask) == timeoutTask)
{
client.PendingAcknowledgments.TryRemove(message.SequenceNumber, out _);
throw new TimeoutException("Message acknowledgment timeout");
}
}
}
catch (Exception ex)
{
Error?.Invoke(this, ex);
DisconnectClient(client);
}
}
public async Task SendDataAsync(ClientConnection client, byte[] data)
{
await SendMessageAsync(client, new NetworkMessage
{
Type = MessageType.Data,
Payload = data
});
}
public async Task SendStringAsync(ClientConnection client, string text)
{
await SendDataAsync(client, Encoding.UTF8.GetBytes(text));
}
public async Task SendFileAsync(ClientConnection client, string filePath)
{
var fileInfo = new FileInfo(filePath);
if (!fileInfo.Exists)
{
throw new FileNotFoundException("File not found", filePath);
}
var fileName = fileInfo.Name;
var fileSize = fileInfo.Length;
// Send start message
var startPayload = Encoding.UTF8.GetBytes($"{fileName}|{fileSize}");
await SendMessageAsync(client, new NetworkMessage
{
Type = MessageType.FileTransferStart,
Payload = startPayload
});
FileTransferStarted?.Invoke(this, (client, filePath, fileSize));
// Send file chunks
using (var fs = File.OpenRead(filePath))
{
var buffer = new byte[_config.FileTransferChunkSize];
int bytesRead;
long totalSent = 0;
while ((bytesRead = await fs.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
var chunk = new byte[bytesRead];
Array.Copy(buffer, chunk, bytesRead);
await SendMessageAsync(client, new NetworkMessage
{
Type = MessageType.FileTransferChunk,
Payload = chunk
});
totalSent += bytesRead;
}
}
// Send end message
await SendMessageAsync(client, new NetworkMessage
{
Type = MessageType.FileTransferEnd,
Payload = Encoding.UTF8.GetBytes(fileName)
});
FileTransferCompleted?.Invoke(this, (client, filePath));
}
private async Task SendFramedDataAsync(Stream stream, byte[] data, CancellationToken ct)
{
switch (_config.Framing)
{
case FramingMode.LengthPrefix:
var lengthBytes = BitConverter.GetBytes(data.Length);
await stream.WriteAsync(lengthBytes, 0, lengthBytes.Length, ct);
await stream.WriteAsync(data, 0, data.Length, ct);
break;
case FramingMode.Delimiter:
await stream.WriteAsync(data, 0, data.Length, ct);
await stream.WriteAsync(_config.Delimiter, 0, _config.Delimiter.Length, ct);
break;
case FramingMode.FixedLength:
case FramingMode.None:
await stream.WriteAsync(data, 0, data.Length, ct);
break;
}
await stream.FlushAsync(ct);
}
private async Task HandleFileTransferAsync(ClientConnection client, NetworkMessage startMessage)
{
try
{
var info = Encoding.UTF8.GetString(startMessage.Payload).Split('|');
var fileName = info[0];
var fileSize = long.Parse(info[1]);
var saveDirectory = _config.FileTransferDirectory ?? Path.GetTempPath();
if (!Directory.Exists(saveDirectory))
{
Directory.CreateDirectory(saveDirectory);
}
var savePath = Path.Combine(saveDirectory, fileName);
// Ensure unique filename
var counter = 1;
var nameWithoutExt = Path.GetFileNameWithoutExtension(fileName);
var extension = Path.GetExtension(fileName);
while (File.Exists(savePath))
{
savePath = Path.Combine(saveDirectory, $"{nameWithoutExt}_{counter}{extension}");
counter++;
}
FileTransferStarted?.Invoke(this, (client, savePath, fileSize));
using (var fs = File.Create(savePath))
{
long totalReceived = 0;
var buffer = ArrayPool<byte>.Shared.Rent(_config.BufferSize);
try
{
while (totalReceived < fileSize && client.IsConnected)
{
var chunkMessage = await ReceiveMessageAsync(client.Stream, buffer, client.CancellationToken.Token);
if (chunkMessage == null)
{
break;
}
if (chunkMessage.Type == MessageType.FileTransferChunk)
{
await fs.WriteAsync(chunkMessage.Payload, 0, chunkMessage.Payload.Length);
totalReceived += chunkMessage.Payload.Length;
}
else if (chunkMessage.Type == MessageType.FileTransferEnd)
{
break;
}
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
FileTransferCompleted?.Invoke(this, (client, savePath));
}
catch (Exception ex)
{
Error?.Invoke(this, ex);
}
}
private void DisconnectClient(ClientConnection client)
{
if (_clients.TryRemove(client.Id, out _))
{
ClientDisconnected?.Invoke(this, client);
client.Dispose();
_connectionSemaphore.Release();
}
}
public void Dispose()
{
_cts?.Cancel();
_listener?.Dispose();
_aesProvider?.Dispose();
foreach (var client in _clients.Values)
{
client.Dispose();
}
_clients.Clear();
}
}
}

View File

@@ -0,0 +1,100 @@
using EonaCat.Transfer.Helpers;
using EonaCat.Transfer.Models;
using System.Net;
using System.Net.Sockets;
namespace EonaCat.Transfer
{
public class UdpClientConnection : IDisposable
{
private readonly NetworkConfig _config;
private UdpClient _udpClient;
private CancellationTokenSource _cts;
private AesEncryptionProvider _aesProvider;
private IPEndPoint _serverEndPoint;
public event EventHandler<NetworkMessage> MessageReceived;
public event EventHandler<Exception> Error;
public UdpClientConnection(NetworkConfig config = null)
{
_config = config ?? new NetworkConfig();
if (_config.AesEncryption?.IsAesEnabled == true)
{
_aesProvider = new AesEncryptionProvider(_config.AesEncryption);
}
}
public async Task ConnectAsync(string host, int port)
{
_cts = new CancellationTokenSource();
_serverEndPoint = new IPEndPoint(IPAddress.Parse(host), port);
_udpClient = new UdpClient();
_udpClient.Connect(_serverEndPoint);
_ = Task.Run(() => ReceiveLoopAsync(_cts.Token));
}
private async Task ReceiveLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
var result = await _udpClient.ReceiveAsync();
var data = result.Buffer;
// Decrypt if enabled
if (_aesProvider != null)
{
data = await _aesProvider.DecryptAsync(data);
}
// Decompress if enabled
if (_config.Compression != CompressionType.None)
{
data = await CompressionHelper.DecompressAsync(data, _config.Compression);
}
var message = NetworkMessage.Deserialize(data);
MessageReceived?.Invoke(this, message);
}
catch (Exception ex)
{
if (!ct.IsCancellationRequested)
{
Error?.Invoke(this, ex);
}
}
}
}
public async Task SendAsync(byte[] data)
{
var message = new NetworkMessage { Type = MessageType.Data, Payload = data };
var serialized = NetworkMessage.Serialize(message);
// Compress if enabled
if (_config.Compression != CompressionType.None)
{
serialized = await CompressionHelper.CompressAsync(serialized, _config.Compression);
}
// Encrypt if enabled
if (_aesProvider != null)
{
serialized = await _aesProvider.EncryptAsync(serialized);
}
await _udpClient.SendAsync(serialized, serialized.Length);
}
public void Dispose()
{
_cts?.Cancel();
_udpClient?.Dispose();
_aesProvider?.Dispose();
}
}
}

View File

@@ -0,0 +1,167 @@
using EonaCat.Transfer.Helpers;
using EonaCat.Transfer.Models;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
namespace EonaCat.Transfer
{
public class UdpServer : IDisposable
{
private readonly NetworkConfig _config;
private UdpClient _udpClient;
private CancellationTokenSource _cts;
private AesEncryptionProvider _aesProvider;
private readonly ConcurrentDictionary<string, DateTime> _knownClients;
public event EventHandler<(IPEndPoint EndPoint, NetworkMessage Message)> MessageReceived;
public event EventHandler<(IPEndPoint EndPoint, Exception Error)> Error;
public event EventHandler<IPEndPoint> ClientDiscovered;
public int KnownClientsCount => _knownClients.Count;
public UdpServer(NetworkConfig config = null)
{
_config = config ?? new NetworkConfig();
_knownClients = new ConcurrentDictionary<string, DateTime>();
if (_config.AesEncryption?.IsAesEnabled == true)
{
_aesProvider = new AesEncryptionProvider(_config.AesEncryption);
}
}
public async Task StartAsync(int port, string bindAddress = "0.0.0.0")
{
_cts = new CancellationTokenSource();
_udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse(bindAddress), port));
_ = Task.Run(() => ReceiveLoopAsync(_cts.Token));
if (_config.EnableKeepAlive)
{
_ = Task.Run(() => CleanupInactiveClientsAsync(_cts.Token));
}
}
private async Task ReceiveLoopAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
var result = await _udpClient.ReceiveAsync();
var data = result.Buffer;
// Decrypt if enabled
if (_aesProvider != null)
{
try
{
data = await _aesProvider.DecryptAsync(data);
}
catch (Exception ex)
{
Error?.Invoke(this, (result.RemoteEndPoint, ex));
continue;
}
}
// Decompress if enabled
if (_config.Compression != CompressionType.None)
{
data = await CompressionHelper.DecompressAsync(data, _config.Compression);
}
var message = NetworkMessage.Deserialize(data);
// Track client
var clientKey = result.RemoteEndPoint.ToString();
if (!_knownClients.ContainsKey(clientKey))
{
_knownClients[clientKey] = DateTime.UtcNow;
ClientDiscovered?.Invoke(this, result.RemoteEndPoint);
}
else
{
_knownClients[clientKey] = DateTime.UtcNow;
}
MessageReceived?.Invoke(this, (result.RemoteEndPoint, message));
}
catch (Exception ex)
{
if (!ct.IsCancellationRequested)
{
Error?.Invoke(this, (null, ex));
}
}
}
}
private async Task CleanupInactiveClientsAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await Task.Delay(_config.KeepAliveIntervalMs, ct);
var timeout = DateTime.UtcNow.AddMilliseconds(-_config.KeepAliveTimeoutMs);
var inactiveClients = _knownClients.Where(kvp => kvp.Value < timeout).Select(kvp => kvp.Key).ToList();
foreach (var client in inactiveClients)
{
_knownClients.TryRemove(client, out _);
}
}
catch { }
}
}
public async Task SendAsync(IPEndPoint endPoint, byte[] data)
{
var message = new NetworkMessage { Type = MessageType.Data, Payload = data };
var serialized = NetworkMessage.Serialize(message);
// Compress if enabled
if (_config.Compression != CompressionType.None)
{
serialized = await CompressionHelper.CompressAsync(serialized, _config.Compression);
}
// Encrypt if enabled
if (_aesProvider != null)
{
serialized = await _aesProvider.EncryptAsync(serialized);
}
await _udpClient.SendAsync(serialized, serialized.Length, endPoint);
}
public async Task BroadcastAsync(byte[] data)
{
var tasks = new List<Task>();
foreach (var client in _knownClients.Keys)
{
var parts = client.Split(':');
var ip = IPAddress.Parse(parts[0]);
var port = int.Parse(parts[1]);
var endPoint = new IPEndPoint(ip, port);
tasks.Add(SendAsync(endPoint, data));
}
await Task.WhenAll(tasks);
}
public void Dispose()
{
_cts?.Cancel();
_udpClient?.Dispose();
_aesProvider?.Dispose();
}
}
}

213
LICENSE
View File

@@ -1,73 +1,204 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
https://EonaCat.com/license/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
OF SOFTWARE BY EONACAT (JEROEN SAEY)
1. Definitions.
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
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
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.
You may obtain a copy of the License at
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

237
README.md
View File

@@ -1,3 +1,236 @@
# EonaCat.Transfer
# EonaCat.Transfer
EonaCat.Transfer
Yet another .NET networking library.
A comprehensive, production-ready networking toolkit providing TCP, UDP, REST, encryption, compression, file transfer, monitoring, and reliability features.
---
- Automatic reconnection handling
- Exponential backoff support
- Reconnection event notifications
- Full connection-state tracking
---
- Client → Server and Server → Client transfers
- Chunked file sending with configurable chunk size
- File transfer progress events
- Automatic unique filename generation
- Customizable save directory
- Foundation for resume support
---
- Supports all framing modes:
- Length-prefix
- Delimiter
- Fixed-length
- None
- AES decryption (optional)
- Robust error handling
- `ArrayPool`-based buffer management
---
- GZip & Deflate compression
- Full async compression/decompression
- Automatic compression in UDP mode
---
- Fully implemented UDP server + client
- Client discovery + tracking
- Broadcast support
- Automatic cleanup of inactive clients
- AES encryption
- Compression integration
---
- Generic result types
- Authentication (Bearer tokens, custom headers)
- File upload/download with progress reporting
- Supports GET, POST, PUT, DELETE
- Progress events for all long-running operations
---
- Reusable TCP connection pool
- Configurable maximum connections
- Automatic connection lifecycle management
- Built-in statistics tracking
---
- `NetworkStatistics` class
- Throughput tracking
- Message counting
- Custom counters
- Formatted and human-readable output
---
- **Message Acknowledgment:** Reliable delivery on demand
- **Message Builder:** Fluent API for message construction
- **Network Helpers:**
- IP discovery
- Port availability checking
- TCP ping
- Latency measurement
- **Metadata Support:** Custom per-connection data storage
- **Enhanced Events:**
- File transfer progress
- Reconnection events
- Error events
---
- Proper disposal and cleanup of all resources
- Thread-safe operations
- Memory efficiency via `ArrayPool`
- Comprehensive error handling
- Timeout management
- NAT-safe keep-alive system
---
# 📘 Usage Examples
### Connection Pool
```csharp
var pool = new TcpConnectionPool("localhost", 8080, maxConnections: 50);
var client = await pool.AcquireAsync();
await client.SendStringAsync("Hello!");
pool.Release(client);
```
### Statistics
```csharp
var stats = new NetworkStatistics();
Console.WriteLine(stats.ToString());
```
## Compression and AES:
```csharp
var config = new NetworkConfig
{
Compression = CompressionType.GZip,
AesEncryption = AesUtilities.CreateFromSharedSecret("MySecret"),
IsMessageAcknowledgmentEnabled = true
};
```
### REST Client
```csharp
var rest = new RestClient();
rest.DownloadProgress += (s, e) =>
Console.WriteLine($"{e.BytesDownloaded}/{e.TotalBytes}");
await rest.DownloadFileAsync(
"https://EonaCat.com/file.zip",
"local.zip"
);
```
## UDP with Encryption
```csharp
var udpServer = new UdpServer(config);
await udpServer.StartAsync(9090);
udpServer.ClientDiscovered += (s, ep) =>
Console.WriteLine($"New client: {ep}");
```
### Network Helpers
```csharp
var ip = NetworkHelper.GetLocalIPAddress();
var port = NetworkHelper.FindAvailablePort();
var latency = await NetworkHelper.GetLatencyAsync("google.com", 443);
Console.WriteLine($"IP: {ip}, Port: {port}, Latency: {latency}ms");
```
# Example:
```csharp
using EonaCat.Transfer;
NetworkConfig networkConfig = new NetworkConfig()
{
Protocol = ProtocolType.TCP,
Framing = FramingMode.Delimiter,
Delimiter = new byte[] { 0x0A }, // LF
EnableKeepAlive = true,
KeepAliveIntervalMs = 15000,
KeepAliveTimeoutMs = 5000,
AutoReconnect = true,
ReconnectDelayMs = 3000,
};
var server = new TcpServer(networkConfig);
server.ClientConnected += Server_ClientConnected;
server.ClientDisconnected += Server_ClientDisconnected;
server.MessageReceived += Server_MessageReceived;
void Server_MessageReceived(object? sender, (ClientConnection Client, NetworkMessage Message) e)
{
string message = System.Text.Encoding.UTF8.GetString(e.Message.Payload);
Console.WriteLine($"Received from {e.Client.Id}: {message}");
// Echo the message back to the client
var responseMessage = new NetworkMessage();
responseMessage.Payload = System.Text.Encoding.UTF8.GetBytes($"Echo: {message}");
server.SendMessageAsync(e.Client, responseMessage);
}
void Server_ClientDisconnected(object? sender, ClientConnection e)
{
Console.WriteLine($"{e.Id} disconnected {e.RemoteEndPoint.ToString()}");
}
void Server_ClientConnected(object? sender, ClientConnection e)
{
Console.WriteLine($"{e.Id} connected {e.RemoteEndPoint.ToString()}");
}
var client = new TcpClient(networkConfig);
client.Connected += Client_Connected;
client.MessageReceived += Client_MessageReceived;
client.Disconnected += Client_Disconnected;
void Client_Disconnected(object? sender, EventArgs e)
{
Console.WriteLine("Client disconnected from server");
}
void Client_MessageReceived(object? sender, NetworkMessage e)
{
string message = System.Text.Encoding.UTF8.GetString(e.Payload);
Console.WriteLine($"Received from server: {message}");
}
void Client_Connected(object? sender, EventArgs e)
{
Console.WriteLine("Client connected to server");
// Send a test message to the server
var message = new NetworkMessage();
message.Payload = System.Text.Encoding.UTF8.GetBytes("Hello, Server!");
client.SendMessageAsync(message);
}
await server.StartAsync(9000);
await client.ConnectAsync("127.0.0.1", 9000);
// Generate traffic
for (int i = 0; i < 10000; i++)
{
var message = new NetworkMessage();
message.Payload = System.Text.Encoding.UTF8.GetBytes($"Message {i + 1} from client");
await client.SendMessageAsync(message);
await Task.Delay(100);
}
Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();
```

BIN
icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB