11 KiB
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:
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<bool> 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<bool> 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<byte>(frame),
SocketFlags.None, cancellationToken);
return true;
}
catch
{
return false;
}
}
public async Task<byte[]?> ReceiveAsync(CancellationToken cancellationToken)
{
if (_socket == null)
return null;
try
{
var buffer = new byte[4096];
var received = await _socket.ReceiveAsync(
new ArraySegment<byte>(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):
// 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:
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:
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 protocolbool IsConnected- Whether currently connectedbool CanRead- Whether data can be readbool CanWrite- Whether data can be written
Core Methods
Task<bool> ConnectAsync(string host, int port, CancellationToken cancellationToken)- Establish connectionTask<bool> SendAsync(byte[] data, CancellationToken cancellationToken)- Send dataTask<byte[]?> ReceiveAsync(CancellationToken cancellationToken)- Receive dataTask DisconnectAsync(CancellationToken cancellationToken)- Close connectionTask CleanupAsync(CancellationToken cancellationToken)- Release resources
Configuration Methods
void ConfigureKeepAlive(bool enabled, int timeInSeconds, int intervalInSeconds, int retryCount)- Configure keep-alivevoid ConfigureSsl(bool useSsl, string? serverName, bool checkRevocation, bool allowRenegotiation)- Configure SSL/TLSvoid ConfigureBufferSize(int bufferSize)- Set buffer sizevoid ConfigureNagle(bool enableNagle)- Configure Nagle's algorithmvoid ConfigureRst(bool enableRst)- Configure RST on close
Utility Methods
string? GetRemoteEndPoint()- Get remote endpoint addressstring? GetLocalEndPoint()- Get local endpoint addressSocket? 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):
public async Task<bool> 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<byte>(frame),
SocketFlags.None, cancellationToken);
return true;
}
Compression Protocol
Implement automatic compression:
public async Task<bool> 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<byte[]?> ReceiveAsync(CancellationToken cancellationToken)
{
byte[] compressed = await ReadCompressedDataAsync(cancellationToken);
// Decompress data after receiving
return DecompressData(compressed);
}
Encryption Protocol
Add encryption on top of transport:
private ICryptoTransform? _encryptor;
private ICryptoTransform? _decryptor;
public async Task<bool> SendAsync(byte[] data, CancellationToken cancellationToken)
{
// Encrypt data before sending
byte[] encrypted = _encryptor.TransformFinalBlock(data, 0, data.Length);
await _socket.SendAsync(new ArraySegment<byte>(encrypted),
SocketFlags.None, cancellationToken);
return true;
}
WebSocket Protocol
Wrap WebSocket for application-level transport:
private WebSocket? _webSocket;
public async Task<bool> 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<bool> SendAsync(byte[] data, CancellationToken cancellationToken)
{
await _webSocket.SendAsync(new ArraySegment<byte>(data),
WebSocketMessageType.Binary, endOfMessage: true, cancellationToken);
return true;
}
Best Practices
- Handle Cancellation: Always respect the CancellationToken parameter
- Error Handling: Return false on send errors, null on receive errors or connection closed
- Resource Cleanup: Ensure Dispose and CleanupAsync properly release resources
- Thread Safety: Use locks if needed for concurrent access
- Configuration: Implement configuration methods even if they're no-ops
- Testing: Test with both NetworkClient and NetworkServer
- Timeouts: Implement connection timeouts in ConnectAsync
- State Management: Track connection state accurately in IsConnected property
API Reference
ProtocolFactory
// Register a custom protocol
ProtocolFactory.RegisterProtocol(string name, Func<INetworkProtocol> 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<string> protocolNames = ProtocolFactory.GetRegisteredProtocols();
// Unregister a protocol (built-in TCP/UDP cannot be unregistered)
ProtocolFactory.UnregisterProtocol("CUSTOM_PROTOCOL");
Configuration
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:
// 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 for complete working examples.
Questions
Contact the brasser