Files
EonaCat.Transfer/README.md
2025-11-21 21:04:44 +01:00

236 lines
5.9 KiB
Markdown

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