# Custom Protocol Support in EonaCat.Connections Custom protocol implementations, allowing you to easily integrate your own protocols (QUIC, HTTP/2, WebSocket, custom binary protocols, etc.) without modifying the core library. ## Quick Start ### Step 1: Implement INetworkProtocol Create a class that implements the `INetworkProtocol` interface: ```csharp using System.Net.Sockets; using EonaCat.Connections.Protocols; public class CustomProtocol : INetworkProtocol { private Socket? _socket; public string ProtocolName => "MyCustomProtocol"; public bool IsConnected => _socket?.Connected == true; public bool CanRead => _socket != null; public bool CanWrite => _socket != null; public async Task ConnectAsync(string host, int port, CancellationToken cancellationToken) { // Implement connection logic _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); var connectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); connectCts.CancelAfter(TimeSpan.FromSeconds(30)); await _socket.ConnectAsync(host, port, connectCts.Token); return true; } public async Task SendAsync(byte[] data, CancellationToken cancellationToken) { if (data?.Length == 0 || _socket == null) return false; try { // Add custom framing, encryption, compression, etc. byte[] frame = PrepareFrame(data); await _socket.SendAsync(new ArraySegment(frame), SocketFlags.None, cancellationToken); return true; } catch { return false; } } public async Task ReceiveAsync(CancellationToken cancellationToken) { if (_socket == null) return null; try { var buffer = new byte[4096]; var received = await _socket.ReceiveAsync( new ArraySegment(buffer), SocketFlags.None, cancellationToken); if (received == 0) return null; // Parse custom framing return ParseFrame(buffer, received); } catch { return null; } } public async Task DisconnectAsync(CancellationToken cancellationToken) { await CleanupAsync(cancellationToken); } public async Task CleanupAsync(CancellationToken cancellationToken) { try { _socket?.Shutdown(SocketShutdown.Both); _socket?.Close(); _socket?.Dispose(); } catch { } _socket = null; await Task.CompletedTask; } // Implement configuration methods (can be no-ops if not applicable to your protocol) public void ConfigureKeepAlive(bool keepAliveEnabled, int timeInSeconds, int intervalInSeconds, int retryCount) { } public void ConfigureSsl(bool useSsl, string? serverName, bool checkCertificateRevocation, bool allowRenegotiation) { } public void ConfigureBufferSize(int bufferSize) { } public void ConfigureNagle(bool enableNagle) { } public void ConfigureRst(bool enableRst) { } public string? GetRemoteEndPoint() => _socket?.RemoteEndPoint?.ToString(); public string? GetLocalEndPoint() => _socket?.LocalEndPoint?.ToString(); public Socket? GetUnderlyingSocket() => _socket; public Stream? GetUnderlyingStream() => null; public void Dispose() { try { _socket?.Dispose(); } catch { } } private byte[] PrepareFrame(byte[] data) { // Implement your custom frame format // Example: add length prefix, checksum, headers, etc. return data; } private byte[]? ParseFrame(byte[] buffer, int length) { // Parse your custom frame format return buffer; } } ``` ### Step 2: Register Your Protocol Register your custom protocol with the factory (optional but recommended): ```csharp // Register with a factory function ProtocolFactory.RegisterProtocol("CUSTOM", () => new CustomProtocol()); // Or with initialization logic ProtocolFactory.RegisterProtocol("CUSTOM_WITH_CONFIG", () => { var protocol = new CustomProtocol(); // Custom initialization return protocol; }); ``` ### Step 3: Use in Configuration Create a configuration that uses your custom protocol: ```csharp var config = new Configuration { Host = "example.com", Port = 8080, // Option 1: Use factory function directly ProtocolFactory = () => new CustomProtocol() // Option 2: Use registered protocol // ProtocolFactory = () => ProtocolFactory.CreateProtocol("CUSTOM") }; // Use with NetworkClient var client = new NetworkClient(config); await client.ConnectAsync(); // Now communicating via your custom protocol! // Or use with NetworkServer var server = new NetworkServer(config); await server.StartAsync(); ``` ### Step 4: Switching Between Protocols Easily switch between protocols at runtime: ```csharp public Configuration CreateConfig(string protocol) { var config = new Configuration { Host = "example.com", Port = 8080, }; config.ProtocolFactory = protocol.ToUpper() switch { "TCP" => () => ProtocolFactory.CreateProtocol("TCP"), "UDP" => () => ProtocolFactory.CreateProtocol("UDP"), "CUSTOM" => () => new CustomProtocol(), _ => () => ProtocolFactory.CreateProtocol("TCP") }; return config; } ``` ## INetworkProtocol Interface Reference Your custom protocol must implement these members: ### Properties - `string ProtocolName` - Returns the name/identifier of your protocol - `bool IsConnected` - Whether currently connected - `bool CanRead` - Whether data can be read - `bool CanWrite` - Whether data can be written ### Core Methods - `Task ConnectAsync(string host, int port, CancellationToken cancellationToken)` - Establish connection - `Task SendAsync(byte[] data, CancellationToken cancellationToken)` - Send data - `Task ReceiveAsync(CancellationToken cancellationToken)` - Receive data - `Task DisconnectAsync(CancellationToken cancellationToken)` - Close connection - `Task CleanupAsync(CancellationToken cancellationToken)` - Release resources ### Configuration Methods - `void ConfigureKeepAlive(bool enabled, int timeInSeconds, int intervalInSeconds, int retryCount)` - Configure keep-alive - `void ConfigureSsl(bool useSsl, string? serverName, bool checkRevocation, bool allowRenegotiation)` - Configure SSL/TLS - `void ConfigureBufferSize(int bufferSize)` - Set buffer size - `void ConfigureNagle(bool enableNagle)` - Configure Nagle's algorithm - `void ConfigureRst(bool enableRst)` - Configure RST on close ### Utility Methods - `string? GetRemoteEndPoint()` - Get remote endpoint address - `string? GetLocalEndPoint()` - Get local endpoint address - `Socket? GetUnderlyingSocket()` - Get underlying socket (return null if not applicable) - `Stream? GetUnderlyingStream()` - Get underlying stream (return null if not applicable) ### Resource Management - `void Dispose()` - Clean up resources (implement IDisposable) ## Use Cases ### Custom Framing Protocol Add protocol-specific framing (length prefixes, checksums, headers): ```csharp public async Task SendAsync(byte[] data, CancellationToken cancellationToken) { // Add 4-byte length prefix byte[] lengthPrefix = BitConverter.GetBytes(data.Length); byte[] frame = new byte[lengthPrefix.Length + data.Length]; Array.Copy(lengthPrefix, frame, lengthPrefix.Length); Array.Copy(data, 0, frame, lengthPrefix.Length, data.Length); await _socket.SendAsync(new ArraySegment(frame), SocketFlags.None, cancellationToken); return true; } ``` ### Compression Protocol Implement automatic compression: ```csharp public async Task SendAsync(byte[] data, CancellationToken cancellationToken) { // Compress data before sending byte[] compressed = CompressData(data); await _stream.WriteAsync(compressed, 0, compressed.Length, cancellationToken); return true; } public async Task ReceiveAsync(CancellationToken cancellationToken) { byte[] compressed = await ReadCompressedDataAsync(cancellationToken); // Decompress data after receiving return DecompressData(compressed); } ``` ### Encryption Protocol Add encryption on top of transport: ```csharp private ICryptoTransform? _encryptor; private ICryptoTransform? _decryptor; public async Task SendAsync(byte[] data, CancellationToken cancellationToken) { // Encrypt data before sending byte[] encrypted = _encryptor.TransformFinalBlock(data, 0, data.Length); await _socket.SendAsync(new ArraySegment(encrypted), SocketFlags.None, cancellationToken); return true; } ``` ### WebSocket Protocol Wrap WebSocket for application-level transport: ```csharp private WebSocket? _webSocket; public async Task ConnectAsync(string host, int port, CancellationToken cancellationToken) { var uri = new Uri($"ws://{host}:{port}"); _webSocket = new ClientWebSocket(); await _webSocket.ConnectAsync(uri, cancellationToken); return true; } public async Task SendAsync(byte[] data, CancellationToken cancellationToken) { await _webSocket.SendAsync(new ArraySegment(data), WebSocketMessageType.Binary, endOfMessage: true, cancellationToken); return true; } ``` ## Best Practices 1. **Handle Cancellation**: Always respect the CancellationToken parameter 2. **Error Handling**: Return false on send errors, null on receive errors or connection closed 3. **Resource Cleanup**: Ensure Dispose and CleanupAsync properly release resources 4. **Thread Safety**: Use locks if needed for concurrent access 5. **Configuration**: Implement configuration methods even if they're no-ops 6. **Testing**: Test with both NetworkClient and NetworkServer 7. **Timeouts**: Implement connection timeouts in ConnectAsync 8. **State Management**: Track connection state accurately in IsConnected property ## API Reference ### ProtocolFactory ```csharp // Register a custom protocol ProtocolFactory.RegisterProtocol(string name, Func factory); // Create a protocol instance INetworkProtocol protocol = ProtocolFactory.CreateProtocol("PROTOCOL_NAME"); INetworkProtocol tcpProtocol = ProtocolFactory.CreateProtocol(ProtocolType.TCP); // Check if registered bool registered = ProtocolFactory.IsProtocolRegistered("PROTOCOL_NAME"); // Get all registered protocol names IEnumerable protocolNames = ProtocolFactory.GetRegisteredProtocols(); // Unregister a protocol (built-in TCP/UDP cannot be unregistered) ProtocolFactory.UnregisterProtocol("CUSTOM_PROTOCOL"); ``` ### Configuration ```csharp var config = new Configuration { // Use custom protocol via factory ProtocolFactory = () => new CustomProtocol(), // Or use enum for built-in protocols (backward compatible) // Protocol = ProtocolType.TCP, Host = "example.com", Port = 8080, BufferSize = 8192, EnableKeepAlive = true, EnableNagle = false, EnableRST = true, // ... other configuration }; // Configuration automatically applies settings to protocol // via GetProtocol() method INetworkProtocol protocol = config.GetProtocol(); ``` ## Backward Compatibility The library maintains full backward compatibility: ```csharp // Old way (still works) var config = new Configuration { Protocol = ProtocolType.TCP // Uses default TCP implementation }; // New way var config = new Configuration { ProtocolFactory = () => ProtocolFactory.CreateProtocol("TCP") }; // Or with custom protocol var config = new Configuration { ProtocolFactory = () => new CustomProtocol() }; ``` ## Examples See [CustomProtocolUsageExample](./CustomProtocolUsageExample.cs) for complete working examples. ## Questions Contact the brasser