Initial version

This commit is contained in:
EonaCat 2025-08-20 20:08:15 +02:00
parent d802217546
commit f08de22c70
21 changed files with 1680 additions and 42 deletions

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.Connections\EonaCat.Connections.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,64 @@
using EonaCat.Connections;
using EonaCat.Connections.Models;
namespace EonaCat.Connections.Client.Example
{
public class Program
{
private static NetworkClient _client;
public static void Main(string[] args)
{
CreateClientAsync().ConfigureAwait(false);
while (true)
{
Console.Write("Enter message to send (or 'exit' to quit): ");
var message = Console.ReadLine();
if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
_client.DisconnectAsync().ConfigureAwait(false);
break;
}
if (!string.IsNullOrEmpty(message))
{
_client.SendAsync(message).ConfigureAwait(false);
}
}
}
private static async Task CreateClientAsync()
{
var config = new Configuration
{
Protocol = ProtocolType.TCP,
Host = "127.0.0.1",
Port = 8080,
UseSsl = true,
UseAesEncryption = true,
ServerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("client.pfx", "p@ss"),
};
_client = new NetworkClient(config);
// Subscribe to events
_client.OnConnected += (sender, e) =>
Console.WriteLine($"Connected to server at {e.RemoteEndPoint}");
_client.OnDataReceived += (sender, e) =>
Console.WriteLine($"Server says: {(e.IsBinary ? $"{e.Data.Length} bytes" : e.StringData)}");
_client.OnDisconnected += (sender, e) =>
Console.WriteLine("Disconnected from server");
await _client.ConnectAsync();
// Send nickname
await _client.SendNicknameAsync("TestUser");
// Send a message
await _client.SendAsync("Hello server!");
}
}
}

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.Connections\EonaCat.Connections.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,75 @@
using EonaCat.Connections;
using EonaCat.Connections.Models;
namespace EonaCat.Connections.Server.Example
{
public class Program
{
private static NetworkServer _server;
public static void Main(string[] args)
{
CreateServerAsync().ConfigureAwait(false);
while (true)
{
Console.Write("Enter message to send (or 'exit' to quit): ");
var message = Console.ReadLine();
if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
_server.Stop();
_server.Dispose();
Console.WriteLine("Server stopped.");
break;
}
if (!string.IsNullOrEmpty(message))
{
_server.BroadcastAsync(message).ConfigureAwait(false);
}
}
}
private static async Task CreateServerAsync()
{
var config = new Configuration
{
Protocol = ProtocolType.TCP,
Port = 8080,
UseSsl = true,
UseAesEncryption = true,
MaxConnections = 100000,
ServerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("server.pfx", "p@ss"),
};
_server = new NetworkServer(config);
// Subscribe to events
_server.OnConnected += (sender, e) =>
Console.WriteLine($"Client {e.ClientId} connected from {e.RemoteEndPoint}");
_server.OnConnectedWithNickname += (sender, e) =>
Console.WriteLine($"Client {e.ClientId} connected with nickname: {e.Nickname}");
_server.OnDataReceived += async (sender, e) =>
{
Console.WriteLine($"Received from {e.ClientId}: {(e.IsBinary ? $"{e.Data.Length} bytes" : e.StringData)}");
// Echo back the message
if (e.IsBinary)
{
await _server.SendToClientAsync(e.ClientId, e.Data);
}
else
{
await _server.SendToClientAsync(e.ClientId, $"Echo: {e.StringData}");
}
};
_server.OnDisconnected += (sender, e) =>
Console.WriteLine($"Client {e.ClientId} disconnected");
await _server.StartAsync();
}
}
}

37
EonaCat.Connections.sln Normal file
View File

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36408.4
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections", "EonaCat.Connections\EonaCat.Connections.csproj", "{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.Client", "EonaCat.Connections.Client\EonaCat.Connections.Client.csproj", "{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.Connections.Server", "EonaCat.Connections.Server\EonaCat.Connections.Server.csproj", "{B0756C21-1D41-041C-D3D7-76A9A01E0009}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D3925D5A-4791-C3BB-93E0-25AC0C0ED425}.Release|Any CPU.Build.0 = Release|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Debug|Any CPU.Build.0 = Debug|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|Any CPU.ActiveCfg = Release|Any CPU
{42A5F58D-850A-8272-4CD9-0B1BEFD12A11}.Release|Any CPU.Build.0 = Release|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B0756C21-1D41-041C-D3D7-76A9A01E0009}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {28C40F0B-3539-41D4-B3F3-9DA55FE9CF1A}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net48; net8.0</TargetFrameworks>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Title>EonaCat.Connections</Title>
<Company>EonaCat (Jeroen Saey)</Company>
<Copyright>EonaCat (Jeroen Saey)</Copyright>
<PackageIcon>EonaCat.png</PackageIcon>
<PackageReadmeFile>readme.md</PackageReadmeFile>
</PropertyGroup>
<ItemGroup>
<None Include="..\EonaCat.png">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Include="..\readme.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,11 @@
using System.Net;
namespace EonaCat.Connections.EventArguments
{
public class ConnectionEventArgs : EventArgs
{
public string ClientId { get; set; }
public IPEndPoint RemoteEndPoint { get; set; }
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
}
}

View File

@ -0,0 +1,11 @@
namespace EonaCat.Connections
{
public class DataReceivedEventArgs : EventArgs
{
public string ClientId { get; set; }
public byte[] Data { get; set; }
public string StringData { get; set; }
public bool IsBinary { get; set; }
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
}
}

View File

@ -0,0 +1,10 @@
namespace EonaCat.Connections.EventArguments
{
public class ErrorEventArgs : EventArgs
{
public string ClientId { get; set; }
public Exception Exception { get; set; }
public string Message { get; set; }
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
}
}

View File

@ -0,0 +1,7 @@
namespace EonaCat.Connections.EventArguments
{
public class NicknameConnectionEventArgs : ConnectionEventArgs
{
public string Nickname { get; set; }
}
}

View File

@ -0,0 +1,131 @@
using System.Security.Cryptography;
using System.Text;
namespace EonaCat.Connections.Helpers
{
public static class AesKeyExchange
{
private static readonly string Pepper = "EonaCat.Connections.Salt";
/// <summary>
/// Send AES key, IV, and salt to the stream.
/// </summary>
/// <param name="stream"></param>
/// <param name="aes"></param>
/// <returns></returns>
public static async Task<Aes> SendAesKeyAsync(Stream stream, Aes aes)
{
var rawKey = aes.Key;
var iv = aes.IV;
var salt = new byte[32];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
// Send raw key, IV, and salt
await WriteBytesWithLengthAsync(stream, rawKey);
await WriteBytesWithLengthAsync(stream, iv);
await WriteBytesWithLengthAsync(stream, salt);
await stream.FlushAsync();
// Derive stronger key using PBKDF2-SHA256 + salt + pepper
var derivedKey = PBKDF2_SHA256(Combine(rawKey, Encoding.UTF8.GetBytes(Pepper)), salt, 100_000, 32);
aes.Key = derivedKey;
return aes;
}
/// <summary>
/// Receive AES key, IV, and salt from the stream and derive the AES key.
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static async Task<Aes> ReceiveAesKeyAsync(Stream stream)
{
var rawKey = await ReadBytesWithLengthAsync(stream);
var iv = await ReadBytesWithLengthAsync(stream);
var salt = await ReadBytesWithLengthAsync(stream);
var derivedKey = PBKDF2_SHA256(Combine(rawKey, Encoding.UTF8.GetBytes(Pepper)), salt, 100_000, 32);
Aes _aesEncryption = Aes.Create();
_aesEncryption.Key = derivedKey;
_aesEncryption.IV = iv;
return _aesEncryption;
}
private static byte[] PBKDF2_SHA256(byte[] password, byte[] salt, int iterations, int outputBytes)
{
using (var hmac = new HMACSHA256(password))
{
int hashLength = hmac.HashSize / 8;
int keyBlocks = (int)Math.Ceiling((double)outputBytes / hashLength);
byte[] output = new byte[outputBytes];
byte[] buffer = new byte[hashLength];
for (int block = 1; block <= keyBlocks; block++)
{
byte[] intBlock = BitConverter.GetBytes(block);
if (BitConverter.IsLittleEndian) Array.Reverse(intBlock);
hmac.Initialize();
hmac.TransformBlock(salt, 0, salt.Length, salt, 0);
hmac.TransformFinalBlock(intBlock, 0, intBlock.Length);
Array.Copy(hmac.Hash, buffer, hashLength);
byte[] temp = (byte[])buffer.Clone();
for (int i = 1; i < iterations; i++)
{
temp = hmac.ComputeHash(temp);
for (int j = 0; j < hashLength; j++)
buffer[j] ^= temp[j];
}
int offset = (block - 1) * hashLength;
int remaining = Math.Min(hashLength, outputBytes - offset);
Array.Copy(buffer, 0, output, offset, remaining);
}
return output;
}
}
private static async Task<byte[]> ReadBytesWithLengthAsync(Stream stream)
{
var lengthBytes = new byte[4];
await ReadExactlyAsync(stream, lengthBytes, 0, 4);
int length = BitConverter.ToInt32(lengthBytes, 0);
var data = new byte[length];
await ReadExactlyAsync(stream, data, 0, length);
return data;
}
private static async Task ReadExactlyAsync(Stream stream, byte[] buffer, int offset, int count)
{
int totalRead = 0;
while (totalRead < count)
{
int read = await stream.ReadAsync(buffer, offset + totalRead, count - totalRead);
if (read == 0) throw new EndOfStreamException("Stream ended prematurely");
totalRead += read;
}
}
private static async Task WriteBytesWithLengthAsync(Stream stream, byte[] data)
{
var lengthBytes = BitConverter.GetBytes(data.Length);
await stream.WriteAsync(lengthBytes, 0, 4);
await stream.WriteAsync(data, 0, data.Length);
}
private static byte[] Combine(byte[] a, byte[] b)
{
var c = new byte[a.Length + b.Length];
Buffer.BlockCopy(a, 0, c, 0, a.Length);
Buffer.BlockCopy(b, 0, c, a.Length, b.Length);
return c;
}
}
}

View File

@ -0,0 +1,27 @@
using System.Security.Cryptography.X509Certificates;
namespace EonaCat.Connections.Models
{
// Configuration class
public class Configuration
{
public bool EnableAutoReconnect { get; set; } = true;
public int ReconnectDelayMs { get; set; } = 5000;
public int MaxReconnectAttempts { get; set; } = 0; // 0 means unlimited attempts
public ProtocolType Protocol { get; set; } = ProtocolType.TCP;
public int Port { get; set; } = 8080;
public string Host { get; set; } = "127.0.0.1";
public bool UseSsl { get; set; } = false;
public X509Certificate2 ServerCertificate { get; set; }
public bool UseAesEncryption { get; set; } = false;
public int BufferSize { get; set; } = 8192;
public int MaxConnections { get; set; } = 100000;
public TimeSpan ConnectionTimeout { get; set; } = TimeSpan.FromSeconds(30);
public bool EnableKeepAlive { get; set; } = true;
public bool EnableNagle { get; set; } = false;
// For testing purposes, allow self-signed certificates
public bool IsSelfSignedEnabled { get; set; } = true;
}
}

View File

@ -0,0 +1,23 @@
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
namespace EonaCat.Connections.Models
{
public class Connection
{
public string Id { get; set; }
public TcpClient TcpClient { get; set; }
public UdpClient UdpClient { get; set; }
public IPEndPoint RemoteEndPoint { get; set; }
public Stream Stream { get; set; }
public string Nickname { get; set; }
public DateTime ConnectedAt { get; set; }
public bool IsSecure { get; set; }
public bool IsEncrypted { get; set; }
public Aes AesEncryption { get; set; }
public CancellationTokenSource CancellationToken { get; set; }
public long BytesSent { get; set; }
public long BytesReceived { get; set; }
}
}

View File

@ -0,0 +1,16 @@
namespace EonaCat.Connections
{
// Connection statistics
public class Stats
{
public int ActiveConnections { get; set; }
public long TotalConnections { get; set; }
public long BytesSent { get; set; }
public long BytesReceived { get; set; }
public long MessagesSent { get; set; }
public long MessagesReceived { get; set; }
public DateTime StartTime { get; set; }
public TimeSpan Uptime => DateTime.UtcNow - StartTime;
public double MessagesPerSecond => MessagesReceived / Math.Max(1, Uptime.TotalSeconds);
}
}

View File

@ -0,0 +1,379 @@
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.Helpers;
using EonaCat.Connections.Models;
using System.Collections.Concurrent;
using System.Net;
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 ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections
{
public class NetworkClient
{
private readonly Configuration _config;
private TcpClient _tcpClient;
private UdpClient _udpClient;
private Stream _stream;
private Aes _aesEncryption;
private CancellationTokenSource _cancellation;
private bool _isConnected;
public event EventHandler<ConnectionEventArgs> OnConnected;
public event EventHandler<DataReceivedEventArgs> OnDataReceived;
public event EventHandler<ConnectionEventArgs> OnDisconnected;
public event EventHandler<ErrorEventArgs> OnSslError;
public event EventHandler<ErrorEventArgs> OnEncryptionError;
public event EventHandler<ErrorEventArgs> OnGeneralError;
public NetworkClient(Configuration config)
{
_config = config;
}
public async Task ConnectAsync()
{
_cancellation = new CancellationTokenSource();
if (_config.Protocol == ProtocolType.TCP)
{
await ConnectTcpAsync();
}
else
{
await ConnectUdp();
}
}
private async Task ConnectTcpAsync()
{
try
{
_tcpClient = new TcpClient();
await _tcpClient.ConnectAsync(_config.Host, _config.Port);
Stream stream = _tcpClient.GetStream();
// Setup SSL if required
if (_config.UseSsl)
{
try
{
var sslStream = new SslStream(stream, false, userCertificateValidationCallback:RemoteCertificateValidationCallback);
await sslStream.AuthenticateAsClientAsync(_config.Host);
stream = sslStream;
}
catch (Exception ex)
{
OnSslError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "SSL authentication failed" });
return;
}
}
// Setup AES encryption if required
if (_config.UseAesEncryption)
{
try
{
_aesEncryption = await AesKeyExchange.ReceiveAesKeyAsync(stream);
}
catch (Exception ex)
{
OnEncryptionError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "AES setup failed" });
return;
}
}
_stream = stream;
_isConnected = true;
OnConnected?.Invoke(this, new ConnectionEventArgs { ClientId = "self", RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port) });
// Start receiving data
_ = Task.Run(() => ReceiveDataAsync(), _cancellation.Token);
}
catch (Exception ex)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Failed to connect" });
}
}
private bool RemoteCertificateValidationCallback(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors)
{
if (_config.IsSelfSignedEnabled)
{
return true; // Accept self-signed certificates
}
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true; // Certificate is valid
}
// Log or handle the SSL error as needed
OnSslError?.Invoke(this, new ErrorEventArgs
{
Exception = new AuthenticationException("SSL certificate validation failed"),
Message = $"SSL Policy Errors: {sslPolicyErrors}"
});
return false; // Reject the certificate
}
private async Task ConnectUdp()
{
try
{
_udpClient = new UdpClient();
_udpClient.Connect(_config.Host, _config.Port);
_isConnected = true;
OnConnected?.Invoke(this, new ConnectionEventArgs { ClientId = "self", RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port) });
// Start receiving data
_ = Task.Run(() => ReceiveUdpDataAsync(), _cancellation.Token);
}
catch (Exception ex)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Failed to connect UDP" });
}
}
private async Task ReceiveDataAsync()
{
var buffer = new byte[_config.BufferSize];
while (!_cancellation.Token.IsCancellationRequested && _isConnected)
{
try
{
var bytesRead = await _stream.ReadAsync(buffer, 0, buffer.Length, _cancellation.Token);
if (bytesRead == 0)
{
break;
}
var data = new byte[bytesRead];
Array.Copy(buffer, data, bytesRead);
await ProcessReceivedDataAsync(data);
}
catch (Exception ex)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Error receiving data" });
_isConnected = false;
// Start reconnect
_ = Task.Run(() => AutoReconnectAsync());
break;
}
}
await DisconnectAsync();
}
private async Task ReceiveUdpDataAsync()
{
while (!_cancellation.Token.IsCancellationRequested && _isConnected)
{
try
{
var result = await _udpClient.ReceiveAsync();
await ProcessReceivedDataAsync(result.Buffer);
}
catch (Exception ex)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Error receiving data" });
_isConnected = false;
// Start reconnect
_ = Task.Run(() => AutoReconnectAsync());
break;
}
}
}
private async Task ProcessReceivedDataAsync(byte[] data)
{
try
{
// Decrypt if AES encryption is enabled
if (_config.UseAesEncryption && _aesEncryption != null)
{
data = await DecryptDataAsync(data, _aesEncryption);
}
// Try to decode as string, fallback to binary
bool isBinary = true;
string stringData = null;
try
{
stringData = Encoding.UTF8.GetString(data);
if (Encoding.UTF8.GetBytes(stringData).Length == data.Length)
{
isBinary = false;
}
}
catch
{
// Keep as binary
}
OnDataReceived?.Invoke(this, new DataReceivedEventArgs
{
ClientId = "server",
Data = data,
StringData = stringData,
IsBinary = isBinary
});
}
catch (Exception ex)
{
if (_config.UseAesEncryption)
{
OnEncryptionError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Error decrypting data" });
}
else
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Error processing received data" });
}
}
}
public async Task SendAsync(byte[] data)
{
if (!_isConnected)
{
return;
}
try
{
// Encrypt if AES encryption is enabled
if (_config.UseAesEncryption && _aesEncryption != null)
{
data = await EncryptDataAsync(data, _aesEncryption);
}
if (_config.Protocol == ProtocolType.TCP)
{
await _stream.WriteAsync(data, 0, data.Length);
await _stream.FlushAsync();
}
else
{
await _udpClient.SendAsync(data, data.Length);
}
}
catch (Exception ex)
{
if (_config.UseAesEncryption)
{
OnEncryptionError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Error encrypting/sending data" });
}
else
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Error sending data" });
}
}
}
public async Task SendAsync(string message)
{
await SendAsync(Encoding.UTF8.GetBytes(message));
}
public async Task SendNicknameAsync(string nickname)
{
await SendAsync($"NICKNAME:{nickname}");
}
private async Task<byte[]> EncryptDataAsync(byte[] data, Aes aes)
{
using (var encryptor = aes.CreateEncryptor())
using (var ms = new MemoryStream())
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
await cs.WriteAsync(data, 0, data.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
private async Task<byte[]> DecryptDataAsync(byte[] data, Aes aes)
{
using (var decryptor = aes.CreateDecryptor())
using (var ms = new MemoryStream(data))
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (var result = new MemoryStream())
{
await cs.CopyToAsync(result);
return result.ToArray();
}
}
private async Task AutoReconnectAsync()
{
if (!_config.EnableAutoReconnect)
{
return;
}
int attempt = 0;
while (!_isConnected && (_config.MaxReconnectAttempts == 0 || attempt < _config.MaxReconnectAttempts))
{
attempt++;
try
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { Message = $"Attempting to reconnect (Attempt {attempt})" });
await ConnectAsync();
if (_isConnected)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { Message = $"Reconnected successfully after {attempt} attempt(s)" });
break;
}
}
catch
{
// Ignore exceptions, we'll retry
}
await Task.Delay(_config.ReconnectDelayMs);
}
if (!_isConnected)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { Message = "Failed to reconnect" });
}
}
public async Task DisconnectAsync()
{
_isConnected = false;
_cancellation?.Cancel();
_tcpClient?.Close();
_udpClient?.Close();
_stream?.Dispose();
_aesEncryption?.Dispose();
OnDisconnected?.Invoke(this, new ConnectionEventArgs { ClientId = "self" });
_ = Task.Run(() => AutoReconnectAsync());
}
public void Dispose()
{
DisconnectAsync().Wait();
_cancellation?.Dispose();
}
}
}

View File

@ -0,0 +1,477 @@
using EonaCat.Connections.EventArguments;
using EonaCat.Connections.Helpers;
using EonaCat.Connections.Models;
using System.Collections.Concurrent;
using System.Net;
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 ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
namespace EonaCat.Connections
{
public class NetworkServer
{
private readonly Configuration _config;
private readonly Stats _stats;
private readonly ConcurrentDictionary<string, Connection> _clients;
private TcpListener _tcpListener;
private UdpClient _udpListener;
private CancellationTokenSource _serverCancellation;
private readonly object _statsLock = new object();
public event EventHandler<ConnectionEventArgs> OnConnected;
public event EventHandler<NicknameConnectionEventArgs> OnConnectedWithNickname;
public event EventHandler<DataReceivedEventArgs> OnDataReceived;
public event EventHandler<ConnectionEventArgs> OnDisconnected;
public event EventHandler<ErrorEventArgs> OnSslError;
public event EventHandler<ErrorEventArgs> OnEncryptionError;
public event EventHandler<ErrorEventArgs> OnGeneralError;
public NetworkServer(Configuration config)
{
_config = config;
_stats = new Stats { StartTime = DateTime.UtcNow };
_clients = new ConcurrentDictionary<string, Connection>();
}
public Stats GetStats()
{
lock (_statsLock)
{
_stats.ActiveConnections = _clients.Count;
return _stats;
}
}
public async Task StartAsync()
{
_serverCancellation = new CancellationTokenSource();
if (_config.Protocol == ProtocolType.TCP)
{
await StartTcpServerAsync();
}
else
{
await StartUdpServerAsync();
}
}
private async Task StartTcpServerAsync()
{
_tcpListener = new TcpListener(IPAddress.Parse(_config.Host), _config.Port);
_tcpListener.Start();
Console.WriteLine($"TCP Server started on {_config.Host}:{_config.Port}");
while (!_serverCancellation.Token.IsCancellationRequested)
{
try
{
var tcpClient = await _tcpListener.AcceptTcpClientAsync();
_ = Task.Run(() => HandleTcpClientAsync(tcpClient), _serverCancellation.Token);
}
catch (ObjectDisposedException)
{
break;
}
catch (Exception ex)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Error accepting TCP client" });
}
}
}
private async Task StartUdpServerAsync()
{
_udpListener = new UdpClient(_config.Port);
Console.WriteLine($"UDP Server started on {_config.Host}:{_config.Port}");
while (!_serverCancellation.Token.IsCancellationRequested)
{
try
{
var result = await _udpListener.ReceiveAsync();
_ = Task.Run(() => HandleUdpDataAsync(result), _serverCancellation.Token);
}
catch (ObjectDisposedException)
{
break;
}
catch (Exception ex)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { Exception = ex, Message = "Error receiving UDP data" });
}
}
}
private async Task HandleTcpClientAsync(TcpClient tcpClient)
{
var clientId = Guid.NewGuid().ToString();
var client = new Connection
{
Id = clientId,
TcpClient = tcpClient,
RemoteEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint,
ConnectedAt = DateTime.UtcNow,
CancellationToken = new CancellationTokenSource()
};
try
{
// Configure TCP client
tcpClient.NoDelay = !_config.EnableNagle;
if (_config.EnableKeepAlive)
{
tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
}
Stream stream = tcpClient.GetStream();
// Setup SSL if required
if (_config.UseSsl)
{
try
{
var sslStream = new SslStream(stream, false, userCertificateValidationCallback:RemoteCertificateValidationCallback);
await sslStream.AuthenticateAsServerAsync(_config.ServerCertificate, false, SslProtocols.Tls12, false);
stream = sslStream;
client.IsSecure = true;
}
catch (Exception ex)
{
OnSslError?.Invoke(this, new ErrorEventArgs { ClientId = clientId, Exception = ex, Message = "SSL authentication failed" });
return;
}
}
// Setup AES encryption if required
if (_config.UseAesEncryption)
{
try
{
client.AesEncryption = Aes.Create();
client.AesEncryption.GenerateKey();
client.AesEncryption.GenerateIV();
client.IsEncrypted = true;
// Securely send raw AES key + IV + salt
await AesKeyExchange.SendAesKeyAsync(stream, client.AesEncryption);
}
catch (Exception ex)
{
OnEncryptionError?.Invoke(this, new ErrorEventArgs
{
ClientId = clientId,
Exception = ex,
Message = "AES setup failed"
});
return;
}
}
client.Stream = stream;
_clients[clientId] = client;
lock (_statsLock)
{
_stats.TotalConnections++;
}
OnConnected?.Invoke(this, new ConnectionEventArgs { ClientId = clientId, RemoteEndPoint = client.RemoteEndPoint });
// Handle client communication
await HandleClientCommunicationAsync(client);
}
catch (Exception ex)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { ClientId = clientId, Exception = ex, Message = "Error handling TCP client" });
}
finally
{
await DisconnectClientAsync(clientId);
}
}
private bool RemoteCertificateValidationCallback(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors)
{
if (_config.IsSelfSignedEnabled)
{
return true; // Accept self-signed certificates
}
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true; // Certificate is valid
}
// Log or handle the SSL error as needed
OnSslError?.Invoke(this, new ErrorEventArgs
{
Exception = new AuthenticationException("SSL certificate validation failed"),
Message = $"SSL Policy Errors: {sslPolicyErrors}"
});
return false; // Reject the certificate
}
private async Task HandleUdpDataAsync(UdpReceiveResult result)
{
var clientKey = result.RemoteEndPoint.ToString();
if (!_clients.TryGetValue(clientKey, out var client))
{
client = new Connection
{
Id = clientKey,
RemoteEndPoint = result.RemoteEndPoint,
ConnectedAt = DateTime.UtcNow
};
_clients[clientKey] = client;
lock (_statsLock)
{
_stats.TotalConnections++;
}
OnConnected?.Invoke(this, new ConnectionEventArgs { ClientId = clientKey, RemoteEndPoint = result.RemoteEndPoint });
}
await ProcessReceivedDataAsync(client, result.Buffer);
}
private async Task HandleClientCommunicationAsync(Connection client)
{
var buffer = new byte[_config.BufferSize];
while (!client.CancellationToken.Token.IsCancellationRequested && client.TcpClient.Connected)
{
try
{
var bytesRead = await client.Stream.ReadAsync(buffer, 0, buffer.Length, client.CancellationToken.Token);
if (bytesRead == 0)
{
break; // Client disconnected
}
var data = new byte[bytesRead];
Array.Copy(buffer, data, bytesRead);
await ProcessReceivedDataAsync(client, data);
}
catch (Exception ex)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { ClientId = client.Id, Exception = ex, Message = "Error reading from client" });
break;
}
}
}
private async Task ProcessReceivedDataAsync(Connection client, byte[] data)
{
try
{
// Decrypt if AES encryption is enabled
if (client.IsEncrypted && client.AesEncryption != null)
{
data = await DecryptDataAsync(data, client.AesEncryption);
}
client.BytesReceived += data.Length;
lock (_statsLock)
{
_stats.BytesReceived += data.Length;
_stats.MessagesReceived++;
}
// Try to decode as string, fallback to binary
bool isBinary = true;
string stringData = null;
try
{
stringData = Encoding.UTF8.GetString(data);
// Check if it's valid UTF-8
if (Encoding.UTF8.GetBytes(stringData).Length == data.Length)
{
isBinary = false;
}
}
catch
{
// Keep as binary
}
// Handle special commands
if (!isBinary && stringData.StartsWith("NICKNAME:"))
{
var nickname = stringData.Substring(9);
client.Nickname = nickname;
OnConnectedWithNickname?.Invoke(this, new NicknameConnectionEventArgs
{
ClientId = client.Id,
RemoteEndPoint = client.RemoteEndPoint,
Nickname = nickname
});
return;
}
OnDataReceived?.Invoke(this, new DataReceivedEventArgs
{
ClientId = client.Id,
Data = data,
StringData = stringData,
IsBinary = isBinary
});
}
catch (Exception ex)
{
if (client.IsEncrypted)
{
OnEncryptionError?.Invoke(this, new ErrorEventArgs { ClientId = client.Id, Exception = ex, Message = "Error decrypting data" });
}
else
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { ClientId = client.Id, Exception = ex, Message = "Error processing received data" });
}
}
}
public async Task SendToClientAsync(string clientId, byte[] data)
{
if (_clients.TryGetValue(clientId, out var client))
{
await SendDataAsync(client, data);
}
}
public async Task SendToClientAsync(string clientId, string message)
{
await SendToClientAsync(clientId, Encoding.UTF8.GetBytes(message));
}
public async Task BroadcastAsync(byte[] data)
{
var tasks = new List<Task>();
foreach (var client in _clients.Values)
{
tasks.Add(SendDataAsync(client, data));
}
await Task.WhenAll(tasks);
}
public async Task BroadcastAsync(string message)
{
await BroadcastAsync(Encoding.UTF8.GetBytes(message));
}
private async Task SendDataAsync(Connection client, byte[] data)
{
try
{
// Encrypt if AES encryption is enabled
if (client.IsEncrypted && client.AesEncryption != null)
{
data = await EncryptDataAsync(data, client.AesEncryption);
}
if (_config.Protocol == ProtocolType.TCP)
{
await client.Stream.WriteAsync(data, 0, data.Length);
await client.Stream.FlushAsync();
}
else
{
await _udpListener.SendAsync(data, data.Length, client.RemoteEndPoint);
}
client.BytesSent += data.Length;
lock (_statsLock)
{
_stats.BytesSent += data.Length;
_stats.MessagesSent++;
}
}
catch (Exception ex)
{
if (client.IsEncrypted)
{
OnEncryptionError?.Invoke(this, new ErrorEventArgs { ClientId = client.Id, Exception = ex, Message = "Error encrypting/sending data" });
}
else
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { ClientId = client.Id, Exception = ex, Message = "Error sending data" });
}
}
}
private async Task<byte[]> EncryptDataAsync(byte[] data, Aes aes)
{
using (var encryptor = aes.CreateEncryptor())
using (var ms = new MemoryStream())
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
await cs.WriteAsync(data, 0, data.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
private async Task<byte[]> DecryptDataAsync(byte[] data, Aes aes)
{
using (var decryptor = aes.CreateDecryptor())
using (var ms = new MemoryStream(data))
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (var result = new MemoryStream())
{
await cs.CopyToAsync(result);
return result.ToArray();
}
}
private async Task DisconnectClientAsync(string clientId)
{
if (_clients.TryRemove(clientId, out var client))
{
try
{
client.CancellationToken?.Cancel();
client.TcpClient?.Close();
client.Stream?.Dispose();
client.AesEncryption?.Dispose();
OnDisconnected?.Invoke(this, new ConnectionEventArgs { ClientId = clientId, RemoteEndPoint = client.RemoteEndPoint });
}
catch (Exception ex)
{
OnGeneralError?.Invoke(this, new ErrorEventArgs { ClientId = clientId, Exception = ex, Message = "Error disconnecting client" });
}
}
}
public void Stop()
{
_serverCancellation?.Cancel();
_tcpListener?.Stop();
_udpListener?.Close();
// Disconnect all clients
var disconnectTasks = new List<Task>();
foreach (var clientId in _clients.Keys.ToArray())
{
disconnectTasks.Add(DisconnectClientAsync(clientId));
}
Task.WaitAll(disconnectTasks.ToArray());
}
public void Dispose()
{
Stop();
_serverCancellation?.Dispose();
}
}
}

View File

@ -0,0 +1,9 @@
namespace EonaCat.Connections
{
// Protocol types
public enum ProtocolType
{
TCP,
UDP
}
}

BIN
EonaCat.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

BIN
EonaCat.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

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.

177
README.md
View File

@ -1,3 +1,178 @@

# EonaCat.Connections
.NET Framework 4.8+ / .NET (Core) compatible library providing high-throughput TCP/UDP
servers and clients with optional TLS (for TCP) and optional application-layer encryption (TCP/UDP).
EonaCat.Connections
## Design goals:
- High performance and low latency
- Scalable to tens of thousands of concurrent connections
- Scalable socket I/O via SocketAsyncEventArgs (SAEA) for raw TCP and UDP
- TLS (SSL) over TCP using SslStream (built-in)
- Optional encryption (AES-CBC + PBKDF2_SHA256) for TCP/UDP payloads
- Minimal allocations, event-driven callbacks
#### - For highest throughput, run x64, enable LargePage, set appropriate Socket options and OS registry tuning.
## Generate self-signed certificate for TLS (TCP):
### Run as Administrator
$cert = New-SelfSignedCertificate `
-DnsName "localhost" `
-CertStoreLocation "Cert:\LocalMachine\My" `
-KeyExportPolicy Exportable `
-NotAfter (Get-Date).AddYears(5) `
-FriendlyName "EonaCat Connections Test Certificate"
$password = ConvertTo-SecureString -String "p@ss" -Force -AsPlainText
Export-PfxCertificate `
-Cert "Cert:\LocalMachine\My\$($cert.Thumbprint)" `
-FilePath "C:\temp\server.pfx" `
-Password $password
#### This will create a self-signed certificate with the password 'p@ss' in the folder C:\temp\server.pfx.
## Server example:
using EonaCat.Connections;
using EonaCat.Connections.Models;
namespace EonaCat.Connections.Server.Example
{
public class Program
{
private static NetworkServer _server;
public static void Main(string[] args)
{
CreateServerAsync().ConfigureAwait(false);
while (true)
{
Console.Write("Enter message to send (or 'exit' to quit): ");
var message = Console.ReadLine();
if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
_server.Stop();
_server.Dispose();
Console.WriteLine("Server stopped.");
break;
}
if (!string.IsNullOrEmpty(message))
{
_server.BroadcastAsync(message).ConfigureAwait(false);
}
}
}
private static async Task CreateServerAsync()
{
var config = new Configuration
{
Protocol = ProtocolType.TCP,
Port = 8080,
UseSsl = true,
UseAesEncryption = true,
MaxConnections = 100000,
ServerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("server.pfx", "p@ss"),
};
_server = new NetworkServer(config);
// Subscribe to events
_server.OnConnected += (sender, e) =>
Console.WriteLine($"Client {e.ClientId} connected from {e.RemoteEndPoint}");
_server.OnConnectedWithNickname += (sender, e) =>
Console.WriteLine($"Client {e.ClientId} connected with nickname: {e.Nickname}");
_server.OnDataReceived += async (sender, e) =>
{
Console.WriteLine($"Received from {e.ClientId}: {(e.IsBinary ? $"{e.Data.Length} bytes" : e.StringData)}");
// Echo back the message
if (e.IsBinary)
{
await _server.SendToClientAsync(e.ClientId, e.Data);
}
else
{
await _server.SendToClientAsync(e.ClientId, $"Echo: {e.StringData}");
}
};
_server.OnDisconnected += (sender, e) =>
Console.WriteLine($"Client {e.ClientId} disconnected");
await _server.StartAsync();
}
}
}
## Client example:
using EonaCat.Connections;
using EonaCat.Connections.Models;
namespace EonaCat.Connections.Client.Example
{
public class Program
{
private static NetworkClient _client;
public static void Main(string[] args)
{
CreateClientAsync().ConfigureAwait(false);
while (true)
{
Console.Write("Enter message to send (or 'exit' to quit): ");
var message = Console.ReadLine();
if (!string.IsNullOrEmpty(message) && message.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
_client.DisconnectAsync().ConfigureAwait(false);
break;
}
if (!string.IsNullOrEmpty(message))
{
_client.SendAsync(message).ConfigureAwait(false);
}
}
}
private static async Task CreateClientAsync()
{
var config = new Configuration
{
Protocol = ProtocolType.TCP,
Host = "127.0.0.1",
Port = 8080,
UseSsl = true,
UseAesEncryption = true,
ServerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("client.pfx", "p@ss"),
};
_client = new NetworkClient(config);
// Subscribe to events
_client.OnConnected += (sender, e) =>
Console.WriteLine($"Connected to server at {e.RemoteEndPoint}");
_client.OnDataReceived += (sender, e) =>
Console.WriteLine($"Server says: {(e.IsBinary ? $"{e.Data.Length} bytes" : e.StringData)}");
_client.OnDisconnected += (sender, e) =>
Console.WriteLine("Disconnected from server");
await _client.ConnectAsync();
// Send nickname
await _client.SendNicknameAsync("TestUser");
// Send a message
await _client.SendAsync("Hello server!");
}
}
}