Initial version

This commit is contained in:
2026-02-06 19:05:53 +01:00
parent f27a69466a
commit 924dfee103
23 changed files with 2190 additions and 64 deletions

27
.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
@@ -83,8 +83,6 @@ StyleCopReport.xml
*.pgc
*.pgd
*.rsp
# but not Directory.Build.rsp, as it configures directory-level build defaults
!Directory.Build.rsp
*.sbr
*.tlb
*.tli
@@ -209,6 +207,9 @@ PublishScripts/
*.nuget.props
*.nuget.targets
# Nuget personal access tokens and Credentials
nuget.config
# Microsoft Azure Build Output
csx/
*.build.csdef
@@ -297,17 +298,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
@@ -364,9 +354,6 @@ ASALocalRun/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
@@ -398,6 +385,7 @@ FodyWeavers.xsd
*.msp
# JetBrains Rider
.idea/
*.sln.iml
# ---> VisualStudioCode
@@ -406,11 +394,8 @@ FodyWeavers.xsd
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
*.code-workspace
# 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>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\EonaCat.JASP\EonaCat.JASP.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,425 @@
using System.Text;
namespace EonaCat.JASP
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("EonaCat.JASP.Tester");
Console.WriteLine("==========================================\n");
Console.WriteLine("Select example to run:");
Console.WriteLine("1. TCP Server/Client (No encryption)");
Console.WriteLine("2. TCP Server/Client with AES Encryption");
Console.WriteLine("3. TCP Server/Client with Authentication");
Console.WriteLine("4. UDP Server/Client");
Console.WriteLine("5. Client-to-Client Messaging");
Console.WriteLine("6. Performance Test (10,000 messages)");
Console.Write("\nEnter choice (1-6): ");
var choice = Console.ReadLine();
switch (choice)
{
case "1":
await RunBasicTcpExample();
break;
case "2":
await RunTcpWithEncryptionExample();
break;
case "3":
await RunTcpWithAuthExample();
break;
case "4":
await RunUdpExample();
break;
case "5":
await RunClientToClientExample();
break;
case "6":
await RunPerformanceTest();
break;
default:
Console.WriteLine("Invalid choice");
break;
}
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
static async Task RunBasicTcpExample()
{
Console.WriteLine("\n=== Basic TCP Example ===\n");
// Create server
var server = new NetworkServer(ProtocolType.TCP, 5000);
server.DataReceived += (s, e) =>
{
var message = Encoding.UTF8.GetString(e.Data);
Console.WriteLine($"[SERVER] Received from {e.FromUsername}: {message}");
// Echo back
server.SendToClient(e.FromUsername, $"Echo: {message}");
};
server.ClientConnected += (s, e) =>
{
Console.WriteLine($"[SERVER] Client connected: {e.Username}");
};
server.ClientDisconnected += (s, e) =>
{
Console.WriteLine($"[SERVER] Client disconnected: {e.Username}");
};
server.ErrorOccurred += (s, e) =>
{
Console.WriteLine($"[SERVER ERROR] {e.Message}: {e.Exception?.Message}");
};
server.Start();
Console.WriteLine("[SERVER] Started on port 5000");
// Wait for server to start
await Task.Delay(500);
// Create client
var client = new NetworkClient(ProtocolType.TCP, "127.0.0.1", 5000);
client.DataReceived += (s, e) =>
{
var message = Encoding.UTF8.GetString(e.Data);
Console.WriteLine($"[CLIENT] Received: {message}");
};
client.Connected += (s, e) =>
{
Console.WriteLine("[CLIENT] Connected to server");
};
client.ErrorOccurred += (s, e) =>
{
Console.WriteLine($"[CLIENT ERROR] {e.Message}: {e.Exception?.Message}");
};
await client.ConnectAsync();
// Send messages
for (int i = 1; i <= 5; i++)
{
client.SendString($"Message {i}");
await Task.Delay(100);
}
await Task.Delay(1000);
// Show stats
Console.WriteLine("\n--- Server Stats ---");
Console.WriteLine(server.GetStats());
Console.WriteLine("\n--- Client Stats ---");
Console.WriteLine(client.GetStats());
// Cleanup
client.Disconnect();
server.Stop();
}
static async Task RunTcpWithEncryptionExample()
{
Console.WriteLine("\n=== TCP with AES Encryption Example ===\n");
var server = new NetworkServer(ProtocolType.TCP, 5001, useAES: true);
server.DataReceived += (s, e) =>
{
var message = Encoding.UTF8.GetString(e.Data);
Console.WriteLine($"[SERVER] Received encrypted message: {message}");
};
server.ClientConnected += (s, e) =>
{
Console.WriteLine($"[SERVER] Client connected with encryption: {e.Username}");
};
server.Start();
Console.WriteLine("[SERVER] Started with AES encryption on port 5001");
await Task.Delay(500);
var client = new NetworkClient(ProtocolType.TCP, "127.0.0.1", 5001, useAES: true);
client.DataReceived += (s, e) =>
{
var message = Encoding.UTF8.GetString(e.Data);
Console.WriteLine($"[CLIENT] Received encrypted message: {message}");
};
await client.ConnectAsync();
client.SendString("This message is encrypted!");
client.SendString("All communication is secure.");
await Task.Delay(1000);
Console.WriteLine("\n--- Server Stats ---");
Console.WriteLine(server.GetStats());
client.Disconnect();
server.Stop();
}
static async Task RunTcpWithAuthExample()
{
Console.WriteLine("\n=== TCP with Authentication Example ===\n");
var server = new NetworkServer(
ProtocolType.TCP,
5002,
username: "ServerAdmin",
password: "SecurePassword123");
server.DataReceived += (s, e) =>
{
var message = Encoding.UTF8.GetString(e.Data);
Console.WriteLine($"[SERVER] Received from authenticated user {e.FromUsername}: {message}");
};
server.ClientConnected += (s, e) =>
{
Console.WriteLine($"[SERVER] Authenticated client: {e.Username}");
};
server.Start();
Console.WriteLine("[SERVER] Started with authentication on port 5002");
await Task.Delay(500);
// Client with correct credentials
var client1 = new NetworkClient(
ProtocolType.TCP,
"127.0.0.1",
5002,
username: "Alice",
password: "SecurePassword123");
await client1.ConnectAsync();
client1.SendString("Hello from authenticated client!");
await Task.Delay(500);
// Try client with wrong credentials (will fail to connect)
try
{
var client2 = new NetworkClient(
ProtocolType.TCP,
"127.0.0.1",
5002,
username: "Hacker",
password: "WrongPassword");
await client2.ConnectAsync();
Console.WriteLine("[CLIENT2] Should not see this - auth should fail");
}
catch (Exception ex)
{
Console.WriteLine($"[CLIENT2] Authentication failed (expected): {ex.Message}");
}
await Task.Delay(1000);
client1.Disconnect();
server.Stop();
}
static async Task RunUdpExample()
{
Console.WriteLine("\n=== UDP Example ===\n");
var server = new NetworkServer(ProtocolType.UDP, 5003);
server.DataReceived += (s, e) =>
{
var message = Encoding.UTF8.GetString(e.Data);
Console.WriteLine($"[SERVER] UDP received: {message}");
};
server.Start();
Console.WriteLine("[SERVER] Started UDP on port 5003");
await Task.Delay(500);
var client = new NetworkClient(ProtocolType.UDP, "127.0.0.1", 5003, username: "UDPClient");
await client.ConnectAsync();
for (int i = 1; i <= 5; i++)
{
client.SendString($"UDP Message {i}");
await Task.Delay(50);
}
await Task.Delay(1000);
Console.WriteLine("\n--- Server Stats ---");
Console.WriteLine(server.GetStats());
client.Disconnect();
server.Stop();
}
static async Task RunClientToClientExample()
{
Console.WriteLine("\n=== Client-to-Client Messaging Example ===\n");
var server = new NetworkServer(ProtocolType.TCP, 5004);
server.DataReceived += (s, e) =>
{
Console.WriteLine($"[SERVER] Routing message from {e.FromUsername} to {e.Message.ToUsername}");
};
server.ClientConnected += (s, e) =>
{
Console.WriteLine($"[SERVER] Client connected: {e.Username}");
server.BroadcastString($"User {e.Username} joined", e.Username);
};
server.Start();
Console.WriteLine("[SERVER] Started on port 5004");
await Task.Delay(500);
// Create multiple clients
var alice = new NetworkClient(ProtocolType.TCP, "127.0.0.1", 5004, username: "Alice");
var bob = new NetworkClient(ProtocolType.TCP, "127.0.0.1", 5004, username: "Bob");
var charlie = new NetworkClient(ProtocolType.TCP, "127.0.0.1", 5004, username: "Charlie");
alice.DataReceived += (s, e) =>
{
var message = Encoding.UTF8.GetString(e.Data);
Console.WriteLine($"[ALICE] Received: {message}");
};
bob.DataReceived += (s, e) =>
{
var message = Encoding.UTF8.GetString(e.Data);
Console.WriteLine($"[BOB] Received: {message}");
};
charlie.DataReceived += (s, e) =>
{
var message = Encoding.UTF8.GetString(e.Data);
Console.WriteLine($"[CHARLIE] Received: {message}");
};
await alice.ConnectAsync();
await Task.Delay(100);
await bob.ConnectAsync();
await Task.Delay(100);
await charlie.ConnectAsync();
await Task.Delay(500);
// Alice sends direct message to Bob
Console.WriteLine("\n[ALICE] Sending direct message to Bob...");
alice.SendToClient("Bob", "Hi Bob, this is Alice!");
await Task.Delay(200);
// Bob sends direct message to Charlie
Console.WriteLine("\n[BOB] Sending direct message to Charlie...");
bob.SendToClient("Charlie", "Hey Charlie, it's Bob!");
await Task.Delay(200);
// Server broadcasts to all
Console.WriteLine("\n[SERVER] Broadcasting to all clients...");
server.BroadcastString("Server announcement: System maintenance in 5 minutes");
await Task.Delay(1000);
Console.WriteLine("\n--- Connected Clients ---");
foreach (var client in server.GetConnectedClients())
{
Console.WriteLine($" - {client.Username} (ID: {client.ClientId})");
}
alice.Disconnect();
bob.Disconnect();
charlie.Disconnect();
server.Stop();
}
static async Task RunPerformanceTest()
{
Console.WriteLine("\n=== Performance Test (10,000 messages) ===\n");
var server = new NetworkServer(ProtocolType.TCP, 5005);
int messagesReceived = 0;
server.DataReceived += (s, e) =>
{
Interlocked.Increment(ref messagesReceived);
};
server.Start();
Console.WriteLine("[SERVER] Started on port 5005");
await Task.Delay(500);
var client = new NetworkClient(ProtocolType.TCP, "127.0.0.1", 5005);
await client.ConnectAsync();
Console.WriteLine("[CLIENT] Connected. Starting performance test...\n");
var startTime = DateTime.UtcNow;
// Send 10,000 messages as fast as possible
var tasks = new Task[10];
int messagesPerTask = 1000;
for (int t = 0; t < 10; t++)
{
int taskId = t;
tasks[t] = Task.Run(() =>
{
for (int i = 0; i < messagesPerTask; i++)
{
client.SendString($"Performance test message {taskId}-{i}");
}
});
}
await Task.WhenAll(tasks);
// Wait for all messages to be received
while (messagesReceived < 10000)
{
await Task.Delay(10);
}
var endTime = DateTime.UtcNow;
var duration = (endTime - startTime).TotalMilliseconds;
Console.WriteLine($"Performance Test Results:");
Console.WriteLine($" Total Messages: 10,000");
Console.WriteLine($" Duration: {duration:N2} ms");
Console.WriteLine($" Messages/second: {(10000 / (duration / 1000)):N2}");
Console.WriteLine($" Average latency: {(duration / 10000):N4} ms per message");
await Task.Delay(500);
Console.WriteLine("\n--- Server Stats ---");
Console.WriteLine(server.GetStats());
Console.WriteLine("\n--- Client Stats ---");
Console.WriteLine(client.GetStats());
client.Disconnect();
server.Stop();
}
}
}

31
EonaCat.JASP.sln Normal file
View File

@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 18
VisualStudioVersion = 18.2.11415.280 d18.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.JASP", "EonaCat.JASP\EonaCat.JASP.csproj", "{2593BDAF-F25E-FCD3-B3BE-BAA7AAC93254}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EonaCat.JASP.Testers", "EonaCat.JASP.Testers\EonaCat.JASP.Testers.csproj", "{C10AB340-CB03-4E3F-AD9E-4F84D83C8C39}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2593BDAF-F25E-FCD3-B3BE-BAA7AAC93254}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2593BDAF-F25E-FCD3-B3BE-BAA7AAC93254}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2593BDAF-F25E-FCD3-B3BE-BAA7AAC93254}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2593BDAF-F25E-FCD3-B3BE-BAA7AAC93254}.Release|Any CPU.Build.0 = Release|Any CPU
{C10AB340-CB03-4E3F-AD9E-4F84D83C8C39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C10AB340-CB03-4E3F-AD9E-4F84D83C8C39}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C10AB340-CB03-4E3F-AD9E-4F84D83C8C39}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C10AB340-CB03-4E3F-AD9E-4F84D83C8C39}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C1A76ED8-9CA1-485E-B2BC-ED234E471293}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,88 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>.netstandard2.1; net8.0; net4.8;</TargetFrameworks>
<ApplicationIcon>icon.ico</ApplicationIcon>
<LangVersion>latest</LangVersion>
<Authors>EonaCat (Jeroen Saey)</Authors>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Company>EonaCat (Jeroen Saey)</Company>
<PackageIcon>icon.png</PackageIcon>
<PackageProjectUrl>https://www.nuget.org/packages/EonaCat.Logger/</PackageProjectUrl>
<Description>EonaCat.JASP is Just Another Socket Package</Description>
<PackageReleaseNotes>Public release version</PackageReleaseNotes>
<Copyright>EonaCat (Jeroen Saey)</Copyright>
<PackageTags>EonaCat;TCP;UDP;Speed;Sockets;Jeroen;Saey</PackageTags>
<PackageIconUrl />
<Version>1.0.0</Version>
<FileVersion>1.0.0</FileVersion>
<PackageReadmeFile>README.md</PackageReadmeFile>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
<Title>EonaCat.JASP</Title>
<RepositoryType>git</RepositoryType>
</PropertyGroup>
<PropertyGroup>
<EVRevisionFormat>1.0.0+{chash:10}.{c:ymd}</EVRevisionFormat>
<EVDefault>true</EVDefault>
<EVInfo>true</EVInfo>
<EVTagMatch>v[0-9]*</EVTagMatch>
<EVRemoveTagV>true</EVRemoveTagV>
<EVVcs>git</EVVcs>
<EVCheckAllAttributes>true</EVCheckAllAttributes>
<EVShowRevision>true</EVShowRevision>
</PropertyGroup>
<PropertyGroup>
<Version>$(GeneratedVersion)</Version>
</PropertyGroup>
<Target Name="EVPack" BeforeTargets="Pack">
<Message Text="EVPack: Forcing NuGet Version = $(GeneratedVersion)" Importance="High" />
<PropertyGroup>
<Version>$(GeneratedVersion)</Version>
</PropertyGroup>
</Target>
<ItemGroup>
<None Remove="icon.png" />
<None Include="..\LICENSE">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Include="..\README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Include="icon.png">
<Pack>True</Pack>
<PackagePath>
</PackagePath>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="EonaCat.Versioning" Version="1.2.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="EonaCat.Versioning.Helpers" Version="1.0.2" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="10.0.2" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<PackageReference Include="System.Threading.Channels" Version="10.0.2" />
</ItemGroup>
<ItemGroup>
<None Update="LICENSE.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Update="README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,10 @@
using System;
namespace EonaCat.JASP.EventArguments
{
public class ClientConnectedEventArgs : EventArgs
{
public string Username { get; set; }
public string ClientId { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
using EonaCat.JASP.Models;
using System;
namespace EonaCat.JASP.EventArguments
{
public class DataReceivedEventArgs : EventArgs
{
public string FromUsername { get; set; }
public byte[] Data { get; set; }
public NetworkMessage Message { get; set; }
}
}

View File

@@ -0,0 +1,10 @@
using System;
namespace EonaCat.JASP.EventArguments
{
public class ErrorEventArgs : EventArgs
{
public Exception Exception { get; set; }
public string Message { get; set; }
}
}

View File

@@ -0,0 +1,68 @@
using System.IO;
using System.Security.Cryptography;
namespace EonaCat.JASP.Helpers
{
public static class EncryptionHelper
{
// AES encryption
public static byte[] EncryptAES(byte[] data, byte[] key, byte[] iv)
{
using (var aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using (var encryptor = aes.CreateEncryptor())
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(data, 0, data.Length);
}
return ms.ToArray();
}
}
}
public static byte[] DecryptAES(byte[] data, byte[] key, byte[] iv)
{
using (var aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
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())
{
cs.CopyTo(result);
return result.ToArray();
}
}
}
public static byte[] GenerateAESKey()
{
using (var aes = Aes.Create())
{
aes.GenerateKey();
return aes.Key;
}
}
public static byte[] GenerateAESIV()
{
using (var aes = Aes.Create())
{
aes.GenerateIV();
return aes.IV;
}
}
}
}

View File

@@ -0,0 +1,81 @@
using EonaCat.JASP.Helpers;
using EonaCat.JASP.Models;
using System.IO;
namespace EonaCat.JASP
{
public static class MessageSerializer
{
public static byte[] Serialize(NetworkMessage message, bool useAES = false, byte[] aesKey = null, byte[] aesIV = null)
{
using (var ms = new MemoryStream())
using (var writer = new BinaryWriter(ms))
{
// Write message type
writer.Write((byte)message.Type);
// Write from username
writer.Write(message.FromUsername ?? string.Empty);
// Write to username
writer.Write(message.ToUsername ?? string.Empty);
// Write data length and data
if (message.Data != null)
{
writer.Write(message.Data.Length);
writer.Write(message.Data);
}
else
{
writer.Write(0);
}
var payload = ms.ToArray();
// Encrypt if needed
if (useAES && aesKey != null && aesIV != null)
{
payload = EncryptionHelper.EncryptAES(payload, aesKey, aesIV);
}
// Add length prefix for TCP
using (var finalMs = new MemoryStream())
using (var finalWriter = new BinaryWriter(finalMs))
{
finalWriter.Write(payload.Length);
finalWriter.Write(payload);
return finalMs.ToArray();
}
}
}
public static NetworkMessage Deserialize(byte[] data, bool useAES = false, byte[] aesKey = null, byte[] aesIV = null)
{
// Decrypt if needed
if (useAES && aesKey != null && aesIV != null)
{
data = EncryptionHelper.DecryptAES(data, aesKey, aesIV);
}
using (var ms = new MemoryStream(data))
using (var reader = new BinaryReader(ms))
{
var message = new NetworkMessage
{
Type = (MessageType)reader.ReadByte(),
FromUsername = reader.ReadString(),
ToUsername = reader.ReadString()
};
var dataLength = reader.ReadInt32();
if (dataLength > 0)
{
message.Data = reader.ReadBytes(dataLength);
}
return message;
}
}
}
}

View File

@@ -0,0 +1,11 @@
namespace EonaCat.JASP
{
public enum MessageType : byte
{
Authentication = 1,
Data = 2,
DirectMessage = 3,
Disconnect = 4,
Acknowledgment = 5
}
}

View File

@@ -0,0 +1,40 @@
using System;
using System.Collections.Concurrent;
namespace EonaCat.JASP.Models
{
public class BufferPool
{
private readonly ConcurrentBag<byte[]> _pool;
private readonly int _bufferSize;
public BufferPool(int bufferSize, int initialCount = 100)
{
_bufferSize = bufferSize;
_pool = new ConcurrentBag<byte[]>();
for (int i = 0; i < initialCount; i++)
{
_pool.Add(new byte[bufferSize]);
}
}
public byte[] Rent()
{
if (_pool.TryTake(out var buffer))
{
return buffer;
}
return new byte[_bufferSize];
}
public void Return(byte[] buffer)
{
if (buffer != null && buffer.Length == _bufferSize)
{
Array.Clear(buffer, 0, buffer.Length);
_pool.Add(buffer);
}
}
}
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Net;
using System.Net.Sockets;
namespace EonaCat.JASP.Models
{
public class ClientInfo
{
public string Username { get; set; }
public string ClientId { get; set; }
public IPEndPoint RemoteEndPoint { get; set; }
public DateTime ConnectedAt { get; set; }
public Socket Socket { get; set; }
public ClientInfo()
{
ConnectedAt = DateTime.UtcNow;
}
}
}

View File

@@ -0,0 +1,18 @@
using System;
namespace EonaCat.JASP.Models
{
public class NetworkMessage
{
public MessageType Type { get; set; }
public string FromUsername { get; set; }
public string ToUsername { get; set; }
public byte[] Data { get; set; }
public DateTime Timestamp { get; set; }
public NetworkMessage()
{
Timestamp = DateTime.UtcNow;
}
}
}

View File

@@ -0,0 +1,41 @@
using System;
namespace EonaCat.JASP.Models
{
public class NetworkStats
{
public long MessagesSent { get; set; }
public long MessagesReceived { get; set; }
public long BytesSent { get; set; }
public long BytesReceived { get; set; }
public long Errors { get; set; }
public DateTime StartTime { get; set; }
public int ActiveConnections { get; set; }
public NetworkStats()
{
StartTime = DateTime.UtcNow;
}
public double GetMessagesPerSecond()
{
var elapsed = (DateTime.UtcNow - StartTime).TotalSeconds;
return elapsed > 0 ? MessagesReceived / elapsed : 0;
}
public override string ToString()
{
var uptime = DateTime.UtcNow - StartTime;
return $"Stats:\n" +
$" Uptime: {uptime}\n" +
$" Messages Sent: {MessagesSent:N0}\n" +
$" Messages Received: {MessagesReceived:N0}\n" +
$" Bytes Sent: {BytesSent:N0}\n" +
$" Bytes Received: {BytesReceived:N0}\n" +
$" Active Connections: {ActiveConnections}\n" +
$" Messages/sec: {GetMessagesPerSecond():N2}\n" +
$" Errors: {Errors:N0}";
}
}
}

View File

@@ -0,0 +1,399 @@
using EonaCat.JASP.EventArguments;
using EonaCat.JASP.Models;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EonaCat.JASP
{
public class NetworkClient
{
public event EventHandler<DataReceivedEventArgs> DataReceived;
public event EventHandler<EventArguments.ErrorEventArgs> ErrorOccurred;
public event EventHandler Connected;
public event EventHandler Disconnected;
private readonly ProtocolType _protocolType;
private readonly string _serverAddress;
private readonly int _port;
private Socket _socket;
private CancellationTokenSource _cts;
private readonly NetworkStats _stats;
private readonly BufferPool _bufferPool;
private bool _isConnected;
// Authentication
private readonly string _username;
private readonly string _password;
// Encryption
private readonly bool _useAES;
private byte[] _aesKey;
private byte[] _aesIV;
// Configuration
private const int BufferSize = 8192;
public string Username => _username;
public bool IsConnected => _isConnected;
public NetworkClient(
ProtocolType protocolType,
string serverAddress,
int port,
string username = null,
string password = null,
bool useAES = false)
{
_protocolType = protocolType;
_serverAddress = serverAddress;
_port = port;
_username = username ?? Guid.NewGuid().ToString();
_password = password;
_useAES = useAES;
_stats = new NetworkStats();
_bufferPool = new BufferPool(BufferSize, 100);
}
public async Task ConnectAsync()
{
_cts = new CancellationTokenSource();
_stats.StartTime = DateTime.UtcNow;
if (_protocolType == ProtocolType.TCP)
{
await ConnectTcpAsync();
}
else
{
ConnectUdp();
}
_isConnected = true;
OnConnected();
}
public void Disconnect()
{
_isConnected = false;
if (_protocolType == ProtocolType.TCP && _socket != null)
{
try
{
var disconnectMsg = new NetworkMessage
{
Type = MessageType.Disconnect,
FromUsername = _username
};
SendMessage(disconnectMsg);
}
catch { }
}
_cts?.Cancel();
_socket?.Close();
_socket?.Dispose();
OnDisconnected();
}
public void SendData(byte[] data)
{
var message = new NetworkMessage
{
Type = MessageType.Data,
FromUsername = _username,
Data = data
};
SendMessage(message);
}
public void SendString(string text)
{
SendData(Encoding.UTF8.GetBytes(text));
}
public void SendToClient(string targetUsername, byte[] data)
{
var message = new NetworkMessage
{
Type = MessageType.DirectMessage,
FromUsername = _username,
ToUsername = targetUsername,
Data = data
};
SendMessage(message);
}
public void SendToClient(string targetUsername, string text)
{
SendToClient(targetUsername, Encoding.UTF8.GetBytes(text));
}
public NetworkStats GetStats()
{
_stats.ActiveConnections = _isConnected ? 1 : 0;
return _stats;
}
private async Task ConnectTcpAsync()
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
_socket.NoDelay = true; // Disable Nagle's algorithm
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
var ipAddress = IPAddress.Parse(_serverAddress);
await _socket.ConnectAsync(ipAddress, _port);
// Authenticate if password is provided
if (!string.IsNullOrEmpty(_password))
{
await AuthenticateAsync();
}
// Receive AES keys if encryption is enabled
if (_useAES)
{
await ReceiveAESKeys(_cts.Token);
}
// Start receiving
_ = Task.Run(() => ReceiveTcpMessages(_cts.Token), _cts.Token);
}
private async Task AuthenticateAsync()
{
var authData = $"{_username}|{_password}";
var authMessage = new NetworkMessage
{
Type = MessageType.Authentication,
FromUsername = _username,
Data = Encoding.UTF8.GetBytes(authData)
};
var serialized = MessageSerializer.Serialize(authMessage, false, null, null);
await _socket.SendAsync(new ArraySegment<byte>(serialized), SocketFlags.None);
}
private async Task ReceiveAESKeys(CancellationToken token)
{
try
{
// Receive key exchange message
var lengthBytes = new byte[4];
await ReceiveExactly(_socket, lengthBytes, 4, token);
var messageLength = BitConverter.ToInt32(lengthBytes, 0);
var messageData = new byte[messageLength];
await ReceiveExactly(_socket, messageData, messageLength, token);
var keyMessage = MessageSerializer.Deserialize(messageData, false, null, null);
// Extract keys (in production, use secure key exchange)
_aesKey = new byte[32]; // 256-bit key
_aesIV = new byte[16]; // 128-bit IV
Array.Copy(keyMessage.Data, 0, _aesKey, 0, 32);
Array.Copy(keyMessage.Data, 32, _aesIV, 0, 16);
}
catch (Exception ex)
{
OnError(ex, "Error receiving AES keys");
}
}
private async Task ReceiveTcpMessages(CancellationToken token)
{
var buffer = _bufferPool.Rent();
try
{
while (!token.IsCancellationRequested && _socket.Connected && _isConnected)
{
try
{
// Read message length
var lengthBytes = new byte[4];
var received = await ReceiveExactly(_socket, lengthBytes, 4, token);
if (received == 0)
{
break;
}
var messageLength = BitConverter.ToInt32(lengthBytes, 0);
if (messageLength <= 0 || messageLength > 10_000_000)
{
break;
}
// Read message payload
var messageData = messageLength <= BufferSize ? buffer : new byte[messageLength];
received = await ReceiveExactly(_socket, messageData, messageLength, token);
if (received == 0)
{
break;
}
var payload = new byte[messageLength];
Array.Copy(messageData, payload, messageLength);
// Process message
ProcessMessage(payload);
}
catch (Exception ex) when (!token.IsCancellationRequested)
{
OnError(ex, "Error receiving TCP message");
break;
}
}
}
finally
{
_bufferPool.Return(buffer);
if (_isConnected)
{
Disconnect();
}
}
}
private async Task<int> ReceiveExactly(Socket socket, byte[] buffer, int length, CancellationToken token)
{
int totalReceived = 0;
while (totalReceived < length && !token.IsCancellationRequested)
{
var received = await socket.ReceiveAsync(
new ArraySegment<byte>(buffer, totalReceived, length - totalReceived),
SocketFlags.None);
if (received == 0)
{
return 0;
}
totalReceived += received;
}
return totalReceived;
}
private void ConnectUdp()
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
var ipAddress = IPAddress.Parse(_serverAddress);
_socket.Connect(ipAddress, _port);
_ = Task.Run(() => ReceiveUdpMessages(_cts.Token), _cts.Token);
}
private async Task ReceiveUdpMessages(CancellationToken token)
{
var buffer = new byte[BufferSize];
while (!token.IsCancellationRequested && _isConnected)
{
try
{
var received = await _socket.ReceiveAsync(
new ArraySegment<byte>(buffer),
SocketFlags.None);
if (received > 4)
{
var messageLength = BitConverter.ToInt32(buffer, 0);
var payload = new byte[messageLength];
Array.Copy(buffer, 4, payload, 0, messageLength);
ProcessMessage(payload);
}
}
catch (Exception ex) when (!token.IsCancellationRequested)
{
OnError(ex, "Error receiving UDP message");
}
}
}
private void ProcessMessage(byte[] payload)
{
try
{
var message = MessageSerializer.Deserialize(payload, _useAES, _aesKey, _aesIV);
_stats.MessagesReceived++;
_stats.BytesReceived += payload.Length;
OnDataReceived(message.FromUsername, message.Data, message);
}
catch (Exception ex)
{
OnError(ex, "Error processing message");
}
}
private void SendMessage(NetworkMessage message)
{
try
{
if (!_isConnected)
{
return;
}
var serialized = MessageSerializer.Serialize(message, _useAES, _aesKey, _aesIV);
if (_protocolType == ProtocolType.TCP)
{
_socket.Send(serialized);
}
else
{
_socket.Send(serialized);
}
_stats.MessagesSent++;
_stats.BytesSent += serialized.Length;
}
catch (Exception ex)
{
OnError(ex, "Error sending message");
}
}
protected virtual void OnDataReceived(string fromUsername, byte[] data, NetworkMessage message)
{
DataReceived?.Invoke(this, new DataReceivedEventArgs
{
FromUsername = fromUsername,
Data = data,
Message = message
});
}
protected virtual void OnError(Exception ex, string message)
{
_stats.Errors++;
ErrorOccurred?.Invoke(this, new EventArguments.ErrorEventArgs
{
Exception = ex,
Message = message
});
}
protected virtual void OnConnected()
{
Connected?.Invoke(this, EventArgs.Empty);
}
protected virtual void OnDisconnected()
{
Disconnected?.Invoke(this, EventArgs.Empty);
}
}
}

View File

@@ -0,0 +1,507 @@
using EonaCat.JASP.EventArguments;
using EonaCat.JASP.Helpers;
using EonaCat.JASP.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EonaCat.JASP
{
public class NetworkServer
{
public event EventHandler<DataReceivedEventArgs> DataReceived;
public event EventHandler<EventArguments.ErrorEventArgs> ErrorOccurred;
public event EventHandler<ClientConnectedEventArgs> ClientConnected;
public event EventHandler<ClientConnectedEventArgs> ClientDisconnected;
private readonly ProtocolType _protocolType;
private readonly int _port;
private Socket _listener;
private CancellationTokenSource _cts;
private readonly ConcurrentDictionary<string, ClientInfo> _clients;
private readonly NetworkStats _stats;
private readonly BufferPool _bufferPool;
// Authentication
private readonly string _serverUsername;
private readonly string _serverPassword;
private readonly bool _requireAuth;
// Encryption
private readonly bool _useAES;
private byte[] _aesKey;
private byte[] _aesIV;
// Configuration
private const int BufferSize = 8192;
private const int MaxPendingConnections = 100;
public NetworkServer(
ProtocolType protocolType,
int port,
string username = null,
string password = null,
bool useAES = false)
{
_protocolType = protocolType;
_port = port;
_clients = new ConcurrentDictionary<string, ClientInfo>();
_stats = new NetworkStats();
_bufferPool = new BufferPool(BufferSize, 1000);
_serverUsername = username;
_serverPassword = password;
_requireAuth = !string.IsNullOrEmpty(password);
_useAES = useAES;
if (_useAES)
{
_aesKey = EncryptionHelper.GenerateAESKey();
_aesIV = EncryptionHelper.GenerateAESIV();
}
}
public void Start()
{
_cts = new CancellationTokenSource();
_stats.StartTime = DateTime.UtcNow;
if (_protocolType == ProtocolType.TCP)
{
StartTcpServer();
}
else
{
StartUdpServer();
}
}
public void Stop()
{
_cts?.Cancel();
_listener?.Close();
_listener?.Dispose();
foreach (var client in _clients.Values)
{
try
{
client.Socket?.Close();
client.Socket?.Dispose();
}
catch { }
}
_clients.Clear();
}
public void SendToClient(string username, byte[] data)
{
if (_clients.TryGetValue(username, out var client))
{
var message = new NetworkMessage
{
Type = MessageType.Data,
FromUsername = _serverUsername ?? "Server",
ToUsername = username,
Data = data
};
SendMessage(client, message);
}
}
public void SendToClient(string username, string text)
{
SendToClient(username, Encoding.UTF8.GetBytes(text));
}
public void BroadcastData(byte[] data, string excludeUsername = null)
{
foreach (var client in _clients.Values)
{
if (client.Username != excludeUsername)
{
SendToClient(client.Username, data);
}
}
}
public void BroadcastString(string text, string excludeUsername = null)
{
BroadcastData(Encoding.UTF8.GetBytes(text), excludeUsername);
}
public NetworkStats GetStats()
{
_stats.ActiveConnections = _clients.Count;
return _stats;
}
public List<ClientInfo> GetConnectedClients()
{
return _clients.Values.ToList();
}
public byte[] GetAESKey() => _aesKey;
public byte[] GetAESIV() => _aesIV;
private void StartTcpServer()
{
_listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
_listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_listener.Bind(new IPEndPoint(IPAddress.Any, _port));
_listener.Listen(MaxPendingConnections);
Task.Run(() => AcceptTcpClients(_cts.Token), _cts.Token);
}
private async Task AcceptTcpClients(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
var clientSocket = await _listener.AcceptAsync();
_ = Task.Run(() => HandleTcpClient(clientSocket, token), token);
}
catch (Exception ex) when (!token.IsCancellationRequested)
{
OnError(ex, "Error accepting TCP client");
}
}
}
private async Task HandleTcpClient(Socket clientSocket, CancellationToken token)
{
var clientId = Guid.NewGuid().ToString();
ClientInfo clientInfo = null;
try
{
clientSocket.NoDelay = true; // Disable Nagle's algorithm for low latency
clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
clientInfo = new ClientInfo
{
ClientId = clientId,
Socket = clientSocket,
RemoteEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint,
Username = clientId
};
// Handle authentication if required
if (_requireAuth)
{
if (!await AuthenticateClient(clientSocket, clientInfo, token))
{
clientSocket.Close();
return;
}
}
_clients.TryAdd(clientInfo.Username, clientInfo);
OnClientConnected(clientInfo.Username, clientInfo.ClientId);
// Send AES keys if encryption is enabled
if (_useAES)
{
await SendAESKeys(clientSocket, token);
}
// Receive loop
var buffer = _bufferPool.Rent();
try
{
while (!token.IsCancellationRequested && clientSocket.Connected)
{
// Read message length (4 bytes)
var lengthBytes = new byte[4];
var received = await ReceiveExactly(clientSocket, lengthBytes, 4, token);
if (received == 0)
{
break;
}
var messageLength = BitConverter.ToInt32(lengthBytes, 0);
if (messageLength <= 0 || messageLength > 10_000_000)
{
break; // Sanity check
}
// Read message payload
var messageData = messageLength <= BufferSize ? buffer : new byte[messageLength];
received = await ReceiveExactly(clientSocket, messageData, messageLength, token);
if (received == 0)
{
break;
}
var payload = new byte[messageLength];
Array.Copy(messageData, payload, messageLength);
// Process message
await ProcessMessage(payload, clientInfo, token);
}
}
finally
{
_bufferPool.Return(buffer);
}
}
catch (Exception ex) when (!token.IsCancellationRequested)
{
OnError(ex, $"Error handling TCP client {clientInfo?.Username}");
}
finally
{
if (clientInfo != null)
{
_clients.TryRemove(clientInfo.Username, out _);
OnClientDisconnected(clientInfo.Username, clientInfo.ClientId);
}
try
{
clientSocket?.Close();
clientSocket?.Dispose();
}
catch { }
}
}
private async Task<int> ReceiveExactly(Socket socket, byte[] buffer, int length, CancellationToken token)
{
int totalReceived = 0;
while (totalReceived < length && !token.IsCancellationRequested)
{
var received = await socket.ReceiveAsync(
new ArraySegment<byte>(buffer, totalReceived, length - totalReceived),
SocketFlags.None);
if (received == 0)
{
return 0;
}
totalReceived += received;
}
return totalReceived;
}
private async Task<bool> AuthenticateClient(Socket socket, ClientInfo clientInfo, CancellationToken token)
{
try
{
// Receive auth message
var lengthBytes = new byte[4];
await ReceiveExactly(socket, lengthBytes, 4, token);
var messageLength = BitConverter.ToInt32(lengthBytes, 0);
var messageData = new byte[messageLength];
await ReceiveExactly(socket, messageData, messageLength, token);
var authMessage = MessageSerializer.Deserialize(messageData, _useAES, _aesKey, _aesIV);
if (authMessage.Type != MessageType.Authentication)
{
return false;
}
var authData = Encoding.UTF8.GetString(authMessage.Data);
var parts = authData.Split('|');
if (parts.Length < 2)
{
return false;
}
var username = parts[0];
var password = parts[1];
if (password != _serverPassword)
{
return false;
}
clientInfo.Username = username;
return true;
}
catch
{
return false;
}
}
private async Task SendAESKeys(Socket socket, CancellationToken token)
{
var keyData = new byte[_aesKey.Length + _aesIV.Length];
Array.Copy(_aesKey, 0, keyData, 0, _aesKey.Length);
Array.Copy(_aesIV, 0, keyData, _aesKey.Length, _aesIV.Length);
var message = new NetworkMessage
{
Type = MessageType.Acknowledgment,
FromUsername = "Server",
Data = keyData
};
var serialized = MessageSerializer.Serialize(message, false, null, null);
await socket.SendAsync(new ArraySegment<byte>(serialized), SocketFlags.None);
}
private void StartUdpServer()
{
_listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
_listener.Bind(new IPEndPoint(IPAddress.Any, _port));
Task.Run(() => ReceiveUdpMessages(_cts.Token), _cts.Token);
}
private async Task ReceiveUdpMessages(CancellationToken token)
{
var buffer = new byte[BufferSize];
while (!token.IsCancellationRequested)
{
try
{
var result = await _listener.ReceiveFromAsync(
new ArraySegment<byte>(buffer),
SocketFlags.None,
new IPEndPoint(IPAddress.Any, 0));
var receivedBytes = result.ReceivedBytes;
var remoteEndPoint = (IPEndPoint)result.RemoteEndPoint;
if (receivedBytes > 4)
{
var messageLength = BitConverter.ToInt32(buffer, 0);
var payload = new byte[messageLength];
Array.Copy(buffer, 4, payload, 0, messageLength);
// Get or create client info
var clientKey = remoteEndPoint.ToString();
var clientInfo = _clients.GetOrAdd(clientKey, _ => new ClientInfo
{
ClientId = Guid.NewGuid().ToString(),
RemoteEndPoint = remoteEndPoint,
Username = clientKey
});
await ProcessMessage(payload, clientInfo, token);
}
}
catch (Exception ex) when (!token.IsCancellationRequested)
{
OnError(ex, "Error receiving UDP message");
}
}
}
private async Task ProcessMessage(byte[] payload, ClientInfo clientInfo, CancellationToken token)
{
try
{
var message = MessageSerializer.Deserialize(payload, _useAES, _aesKey, _aesIV);
_stats.MessagesReceived++;
_stats.BytesReceived += payload.Length;
switch (message.Type)
{
case MessageType.Data:
OnDataReceived(message.FromUsername, message.Data, message);
break;
case MessageType.DirectMessage:
// Route to specific client
if (_clients.TryGetValue(message.ToUsername, out var targetClient))
{
await Task.Run(() => SendMessage(targetClient, message), token);
}
break;
case MessageType.Disconnect:
_clients.TryRemove(clientInfo.Username, out _);
break;
}
}
catch (Exception ex)
{
OnError(ex, "Error processing message");
}
}
private void SendMessage(ClientInfo client, NetworkMessage message)
{
try
{
var serialized = MessageSerializer.Serialize(message, _useAES, _aesKey, _aesIV);
if (_protocolType == ProtocolType.TCP && client.Socket != null)
{
client.Socket.Send(serialized);
}
else if (_protocolType == ProtocolType.UDP && client.RemoteEndPoint != null)
{
_listener.SendTo(serialized, client.RemoteEndPoint);
}
_stats.MessagesSent++;
_stats.BytesSent += serialized.Length;
}
catch (Exception ex)
{
OnError(ex, $"Error sending message to {client.Username}");
}
}
protected virtual void OnDataReceived(string fromUsername, byte[] data, NetworkMessage message)
{
DataReceived?.Invoke(this, new DataReceivedEventArgs
{
FromUsername = fromUsername,
Data = data,
Message = message
});
}
protected virtual void OnError(Exception ex, string message)
{
_stats.Errors++;
ErrorOccurred?.Invoke(this, new EventArguments.ErrorEventArgs
{
Exception = ex,
Message = message
});
}
protected virtual void OnClientConnected(string username, string clientId)
{
ClientConnected?.Invoke(this, new ClientConnectedEventArgs
{
Username = username,
ClientId = clientId
});
}
protected virtual void OnClientDisconnected(string username, string clientId)
{
ClientDisconnected?.Invoke(this, new ClientConnectedEventArgs
{
Username = username,
ClientId = clientId
});
}
}
}

View File

@@ -0,0 +1,8 @@
namespace EonaCat.JASP
{
public enum ProtocolType
{
TCP,
UDP
}
}

BIN
EonaCat.JASP/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

BIN
EonaCat.JASP/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

5
EonaCat.JASP/libman.json Normal file
View File

@@ -0,0 +1,5 @@
{
"version": "1.0",
"defaultProvider": "cdnjs",
"libraries": []
}

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 2026 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.

226
README.md
View File

@@ -1,3 +1,225 @@
# EonaCat.JASP
# EonaCat.JASP Network Library
EonaCat.JASP
### Basic TCP Server
```csharp
using EonaCat.JASP;
var server = new NetworkServer(ProtocolType.TCP, 5000);
server.DataReceived += (s, e) =>
{
var message = Encoding.UTF8.GetString(e.Data);
Console.WriteLine($"Received: {message}");
};
server.Start();
```
### Basic TCP Client
```csharp
var client = new NetworkClient(ProtocolType.TCP, "127.0.0.1", 5000);
client.DataReceived += (s, e) =>
{
var message = Encoding.UTF8.GetString(e.Data);
Console.WriteLine($"Received: {message}");
};
await client.ConnectAsync();
client.SendString("Hello, Server!");
```
## Advanced
### Server with Authentication
```csharp
var server = new NetworkServer(
ProtocolType.TCP,
5000,
username: "ServerAdmin",
password: "SecurePassword123"
);
server.ClientConnected += (s, e) =>
{
Console.WriteLine($"Authenticated client: {e.Username}");
};
server.Start();
```
### Client with Authentication
```csharp
var client = new NetworkClient(
ProtocolType.TCP,
"127.0.0.1",
5000,
username: "Alice",
password: "SecurePassword123"
);
await client.ConnectAsync();
```
### Server with AES Encryption
```csharp
var server = new NetworkServer(
ProtocolType.TCP,
5000,
useAES: true
);
server.Start();
```
### Client with AES Encryption
```csharp
var client = new NetworkClient(
ProtocolType.TCP,
"127.0.0.1",
5000,
useAES: true
);
await client.ConnectAsync();
```
### UDP Server/Client
```csharp
// Server
var server = new NetworkServer(ProtocolType.UDP, 5000);
server.Start();
// Client
var client = new NetworkClient(ProtocolType.UDP, "127.0.0.1", 5000);
await client.ConnectAsync();
```
### Client-to-Client Messaging
```csharp
// On Client 1 (Alice)
alice.SendToClient("Bob", "Hi Bob!");
// On Client 2 (Bob)
bob.DataReceived += (s, e) =>
{
if (e.FromUsername == "Alice")
{
Console.WriteLine($"Message from Alice: {Encoding.UTF8.GetString(e.Data)}");
}
};
```
### Broadcasting to All Clients
```csharp
// Server broadcasts to all connected clients
server.BroadcastString("Server announcement!");
// Broadcast to all except one client
server.BroadcastString("Message", excludeUsername: "Alice");
```
### Send Binary Data
```csharp
// Send byte array
byte[] imageData = File.ReadAllBytes("image.jpg");
client.SendData(imageData);
// Send to specific client
client.SendToClient("Bob", imageData);
```
### Network Statistics
```csharp
// Get server stats
var serverStats = server.GetStats();
Console.WriteLine(serverStats);
// Output:
// Stats:
// Uptime: 00:05:23
// Messages Sent: 15,234
// Messages Received: 15,234
// Bytes Sent: 1,523,400
// Bytes Received: 1,523,400
// Active Connections: 5
// Messages/sec: 47.23
// Errors: 0
// Get client stats
var clientStats = client.GetStats();
Console.WriteLine(clientStats);
```
### Get Connected Clients
```csharp
var clients = server.GetConnectedClients();
foreach (var client in clients)
{
Console.WriteLine($"{client.Username} - {client.RemoteEndPoint}");
}
```
## Event Handlers
### Server Events
```csharp
server.DataReceived += (s, e) =>
{
// Handle received data
Console.WriteLine($"From: {e.FromUsername}");
Console.WriteLine($"Data: {Encoding.UTF8.GetString(e.Data)}");
};
server.ClientConnected += (s, e) =>
{
Console.WriteLine($"Client connected: {e.Username} ({e.ClientId})");
};
server.ClientDisconnected += (s, e) =>
{
Console.WriteLine($"Client disconnected: {e.Username}");
};
server.ErrorOccurred += (s, e) =>
{
Console.WriteLine($"Error: {e.Message}");
Console.WriteLine($"Exception: {e.Exception}");
};
```
### Client Events
```csharp
client.DataReceived += (s, e) =>
{
// Handle received data
};
client.Connected += (s, e) =>
{
Console.WriteLine("Connected to server");
};
client.Disconnected += (s, e) =>
{
Console.WriteLine("Disconnected from server");
};
client.ErrorOccurred += (s, e) =>
{
Console.WriteLine($"Error: {e.Message}");
};
```