2026-11-04 09:43:24 +01:00
2026-11-04 07:53:40 +01:00
2026-11-04 07:53:40 +01:00
2026-11-04 09:39:40 +01:00
2026-11-04 07:53:40 +01:00
2026-11-04 09:43:24 +01:00
2026-11-04 07:53:40 +01:00
2026-11-04 07:53:40 +01:00
2026-11-04 09:43:24 +01:00
2026-11-04 07:53:40 +01:00
2026-11-04 07:53:40 +01:00
2026-11-04 09:43:24 +01:00
2026-11-04 07:53:40 +01:00
2026-11-04 07:53:40 +01:00
2026-11-04 09:43:24 +01:00
2026-11-04 07:53:40 +01:00
2026-11-04 07:53:40 +01:00
2026-11-04 07:53:40 +01:00
2026-11-04 07:53:40 +01:00
2025-08-20 20:07:43 +02:00
2026-11-04 07:53:40 +01:00
2025-08-20 20:08:15 +02:00
2025-08-20 20:08:15 +02:00
2026-06-17 08:05:50 +02:00
2026-11-04 09:43:24 +01:00
2026-11-04 07:53:40 +01:00

EonaCat.Connections

EonaCat.Connections is an asynchronous .NET library for building TCP and UDP clients and servers. It provides connection lifecycle management, message framing, optional encryption, events, heartbeat handling, diagnostics, and configurable server-side protections.

Install

dotnet add package EonaCat.Connections

Or use the NuGet Package Manager:

Install-Package EonaCat.Connections

The main types are in the EonaCat.Connections namespace. Configuration and protocol enums are in EonaCat.Connections.Models.

Features

  • TCP and UDP clients and servers.
  • Async connect, send, disconnect, start, and stop APIs, with cancellation-token overloads for send operations.
  • String (UTF-8) and binary payloads.
  • Optional delimiter and length-prefixed message framing.
  • Optional TLS and AES payload encryption.
  • Client automatic reconnect, configurable SSL retries, TCP keep-alive, and optional ping/pong heartbeat.
  • Events for connection lifecycle, data, errors, client nicknames, and heartbeat responses.
  • Server unicast, broadcast, client-to-client forwarding, and request/response helpers.
  • Server connection limits, statistics, security metrics, health/status reporting, and optional HTML reports.
  • Configurable server-side rate limiting, payload validation, IP filtering, DDoS and Slowloris detection.
  • TCP/UDP protocol implementations plus a low-level named protocol factory for custom transport code.

Quick Start

The following examples use TCP, UTF-8 messages, and no transport encryption. Start the server before connecting the client.

Server

using EonaCat.Connections;
using EonaCat.Connections.Models;

var configuration = new Configuration
{
    Protocol = ProtocolType.TCP,
    Host = "127.0.0.1",
    Port = 5050
};

using var server = new NetworkServer(configuration);

server.OnConnected += (_, connection) =>
    Console.WriteLine($"Connected: {connection.ClientId} from {connection.RemoteEndPoint}");

server.OnDataReceived += async (_, message) =>
{
    Console.WriteLine($"Received from {message.ClientId}: {message.StringData}");
    await server.SendToClientAsync(message.ClientId, $"Echo: {message.StringData}");
};

server.OnDisconnected += (_, connection) =>
    Console.WriteLine($"Disconnected: {connection.ClientId} ({connection.Reason})");

await server.StartAsync();
Console.WriteLine("Listening. Press Ctrl+C to stop.");

using var stop = new CancellationTokenSource();
Console.CancelKeyPress += (_, eventArgs) =>
{
    eventArgs.Cancel = true;
    stop.Cancel();
};

try
{
    await Task.Delay(Timeout.Infinite, stop.Token);
}
catch (OperationCanceledException)
{
    // Ctrl+C requested shutdown.
}
finally
{
    await server.StopAsync();
}

StartAsync() starts the listener and returns; it does not block until the server stops. Use StopAsync() for an awaited shutdown.

Client

using EonaCat.Connections;
using EonaCat.Connections.Models;

var configuration = new Configuration
{
    Protocol = ProtocolType.TCP,
    Host = "127.0.0.1",
    Port = 5050,
    EnableAutoReconnect = true
};

using var client = new NetworkClient(configuration);

client.OnConnected += (_, connection) =>
    Console.WriteLine($"Connected to {connection.RemoteEndPoint}");

client.OnDataReceived += (_, message) =>
    Console.WriteLine($"Server replied: {message.StringData}");

client.OnDisconnected += (_, connection) =>
    Console.WriteLine($"Disconnected: {connection.Reason}");

if (await client.ConnectAsync())
{
    await client.SendAsync("Hello from the client");
}

await client.DisconnectAsync();

ConnectAsync() returns whether the connection succeeded. WaitForConnectedAsync(timeout, cancellationToken) can be used to await the next successful connection event. Dispose clients when finished.

Sending and Receiving

Text and binary data

String overloads encode and decode UTF-8. Use byte-array overloads for binary protocols or when the application owns serialization:

byte[] payload = [0x01, 0x02, 0x03];
await client.SendAsync(payload, cancellationToken);

await server.SendToClientAsync(clientId, payload, cancellationToken);
await server.BroadcastAsync("Service maintenance in five minutes");

DataReceivedEventArgs provides Data (raw bytes), StringData (UTF-8 text), IsBinary, ClientId, Nickname, RemoteEndPoint, and Timestamp.

Request and response

The convenience methods send data and wait for the next matching received message. The default timeout is 30 seconds; pass a timeout and cancellation token to override it.

var response = await client.SendAndWaitForResponseAsync(
    "status",
    timeout: TimeSpan.FromSeconds(5),
    cancellationToken);

if (response is not null)
{
    Console.WriteLine(response.StringData);
}

On the server, use SendToClientAndWaitForResponseAsync, SendFromClientToClientAndWaitForResponseAsync, or BroadcastAndWaitForResponsesAsync. These helpers do not define application-level request IDs. If concurrent requests can overlap, include a correlation ID in your protocol and match responses in your application.

Nicknames and client addressing

Clients can send or update a nickname with SendNicknameAsync("worker-1"). The server raises OnConnectedWithNickname when it receives a nickname. Server send methods can address a client by its client ID, endpoint, or nickname. GetClient(clientId) returns the connected client matches; GetClients() returns the client registry.

await client.SendNicknameAsync("worker-1");
await server.SendToClientAsync("worker-1", "You are registered");

The server can also forward data to another client with SendFromClientToClientAsync(fromClientId, toClientId, data). The server sends to the destination; the fromClientId identifies the source for missing-client diagnostics.

Connection management

ConnectAsync() returns true when the initial connection succeeds. WaitForConnectedAsync(timeout, cancellationToken) waits for a successful client connection event and returns false if the wait ends without a connection. IsConnected, ConnectionTime, Uptime, LastActive, LastDataSent, LastDataReceived, BytesSent, BytesReceived, MessagesSent, and MessagesReceived expose client state and counters. Idle and connected durations are also available as TimeSpan, integer units, or formatted strings.

When enabled, client auto-reconnect starts after a client has connected once and a later connection is lost. A client-requested disconnect stops reconnecting. MaxReconnectAttempts = 0 removes the configured attempt limit for a reconnect sequence; repeated sequences are still bounded by the client's consecutive-failure protection. SSL/TLS connection retries are controlled separately by SSLMaxRetries, SSLRetryDelayInSeconds, and the retry-delay settings. A zero SSL retry count means the retry loop has no configured maximum, so use cancellation or a finite limit when indefinite retries are not appropriate.

On the server, WaitForClientAsync(clientId, timeout, cancellationToken) waits for a client with that exact ID. DisconnectClientAsync removes a client and records the supplied DisconnectReason. GetClient(clientId) can resolve a client ID, nickname, or remote endpoint; endpoint hostnames are resolved to addresses, and a nickname shared by multiple clients can return more than one result. GetClients() returns the registry. Send methods return false when there is no matching connected client or when no send succeeds; a missing target also raises OnClientMissing.

Server unicast, broadcast, and client-to-client forwarding have byte and UTF-8 string overloads. Send and response helpers accept timeouts and cancellation tokens. BroadcastAndWaitForResponsesAsync collects responses until the timeout or expected response count; these helpers do not correlate overlapping application requests, so include your own request ID when concurrent calls are possible. With UDP, a client registry entry is keyed by its endpoint and exists after the first datagram; UDP still does not provide a reliable session or delivery guarantee.

Message Framing

TCP is a byte stream; a single send is not guaranteed to arrive as one receive operation. MessageFraming.None (the default) forwards received data without reconstructing application message boundaries. Choose framing when each received event must represent one complete message, and configure both ends consistently.

var configuration = new Configuration
{
    Protocol = ProtocolType.TCP,
    Host = "127.0.0.1",
    Port = 5050,
    MessageFraming = FramingMode.LengthPrefixed,
    LengthPrefixedLength = 4,
    UseBigEndian = true,
    MAX_MESSAGE_SIZE = 1024 * 1024
};

Available modes:

  • FramingMode.None: no message-boundary reconstruction.
  • FramingMode.LengthPrefixed: a length header followed by the payload. Prefix sizes from 1 to 8 bytes are supported. The default is 4 bytes; UseBigEndian controls byte order and defaults to false (little-endian).
  • FramingMode.Delimiter: payloads end at a delimiter. The default delimiter is %. Servers also expose SetSeparator(string) and SetSeparator(byte[]); configure the same delimiter on both peers.

MAX_MESSAGE_SIZE limits message payload size. It is not a substitute for application-level validation.

Protocols and Encryption

TCP and UDP

Set Configuration.Protocol to ProtocolType.TCP or ProtocolType.UDP. TCP supports stream-oriented communication and the library's TLS option. UDP is datagram-oriented and does not provide TCP's delivery or ordering guarantees. For UDP broadcast, set EnableBroadcast = true where applicable.

TLS

TLS is enabled by configuring an X509Certificate2 on Configuration; certificate validation and client-certificate behavior are controlled by the certificate and TLS settings. Configure valid certificates and trust on the communicating peers. Do not enable IsSelfSignedEnabled in production: it accepts certificates without normal certificate validation. TrustedThumbprints, CheckCertificateRevocation, MutuallyAuthenticate, AdditionalCertificates, and AllowTlsRenegotiation provide additional certificate and handshake controls.

AES encryption

Set UseAesEncryption = true and provide an AesPassword on both peers to enable the library's AES key exchange and payload encryption. Keep the password secret and deliver it through a secure configuration mechanism; do not commit it to source control. TLS is generally preferable for protecting data in transit and authenticating the remote endpoint.

Custom protocol abstractions

NetworkClient and NetworkServer currently select only ProtocolType.TCP or ProtocolType.UDP; they do not call Configuration.GetProtocol() or use ProtocolFactory to replace their transport. The protocol interface and registry are available for applications that create and manage protocol instances directly. Configuration.GetProtocol() creates an instance from ProtocolFactory or the built-in registry and applies the configured buffer, Nagle, reset, broadcast, keep-alive, and SSL options.

To register and create a protocol instance:

using EonaCat.Connections.Models;
using EonaCat.Connections.Protocols;

ProtocolFactory.RegisterProtocol("CUSTOM", () => new MyNetworkProtocol());

var configuration = new Configuration
{
    Host = "example.net",
    Port = 7000,
    ProtocolFactory = () => ProtocolFactory.CreateProtocol("CUSTOM")
};

using var protocol = configuration.GetProtocol();
byte[] payload = [0x01, 0x02, 0x03];
using var cancellation = new CancellationTokenSource();
var cancellationToken = cancellation.Token;
if (await protocol.ConnectAsync(configuration.Host, configuration.Port, cancellationToken))
{
    await protocol.SendAsync(payload, cancellationToken);
}

INetworkProtocol defines connection, send/receive, cleanup, configuration, and endpoint/socket access members. ProtocolFactory can register, create, query, list, and unregister custom registrations; built-in TCP and UDP registrations cannot be removed. Return a fresh disposable instance for each independent connection. Implement the configuration hooks your protocol supports; IBroadcastConfigurableProtocol adds the optional broadcast hook. This low-level API does not automatically add core message framing, lifecycle events, client registry, reconnect, or server send helpers to the custom transport. See Custom Crap/CUSTOMPROTOCOLS.md for the interface implementation example.

Server Protections

Server controls are configured through Configuration.Security (SecurityOptions). Implemented protections include:

  • Global and per-connection message rate limits.
  • Payload size, empty-message, null-byte, and suspicious-content checks.
  • DDoS and Slowloris detection.
  • IP allow/deny lists, temporary blocking, and automatic blocking after violations.
  • Security logging and counters for enabled protections.

Example:

var configuration = new Configuration
{
    Host = "0.0.0.0",
    Port = 5050,
    Security = new SecurityOptions
    {
        EnableGlobalRateLimiting = true,
        GlobalMessagesPerSecond = 20_000,
        EnablePerConnectionRateLimiting = true,
        ConnectionMessagesPerSecond = 2_000,
        EnablePayloadValidation = true,
        MaxPayloadSize = 1024 * 1024,
        EnableIPFiltering = true,
        WhitelistedIPs = new HashSet<string> { "127.0.0.1" }
    }
};

SecurityOptions enables global and per-connection rate limiting, security logging, and null-byte blocking by default. Payload validation, suspicious-content detection, DDoS detection, Slowloris detection, and IP filtering default to disabled. The controls apply to server-side incoming connections and messages; they do not provide user authentication or authorization. Tune limits for the expected traffic and payload profile. These controls complement, but do not replace, operating-system firewalls, network-layer protections, or application authorization.

Security setting Default Effect when implemented
EnableGlobalRateLimiting, GlobalMessagesPerSecond true, 50000 Caps the aggregate incoming message rate.
EnablePerConnectionRateLimiting, ConnectionMessagesPerSecond true, 10000 Caps messages per client connection.
EnablePayloadValidation, MaxPayloadSize false, 50 MiB Rejects payloads above this configured size when validation is enabled. The core MAX_MESSAGE_SIZE remains a separate limit.
ValidateMessageNotEmpty false Rejects empty payloads independently of the size-validation toggle.
BlockNullBytePayloads true Rejects payloads containing a zero byte. Disable it for binary protocols that legitimately use zero bytes.
EnableSuspiciousContentDetection false Checks valid UTF-8 text for SQL-like, script, and path-traversal patterns. Invalid UTF-8 binary payloads are not scanned. Pattern matching is heuristic, not application-level validation.
EnableDDoSDetection, MaxConnectionsPerSecondPerIp, ConnectionSpamThreshold, SpamDetectionWindowSeconds false, 100, 10, 5 Tracks connection attempts by IP and can reject traffic classified as suspicious.
EnableSlowlorisDetection, SlowlorisMinBytesPerSecond, SlowlorisDetectionWindowSeconds false, 1024, 30 Detects clients whose received-byte rate falls below the configured threshold.
EnableIPFiltering, WhitelistedIPs, BlacklistedIPs false, empty, empty Enables IP allow/deny lists. Explicitly configure the lists before enabling filtering.
AutoBlockIPAfterViolations, IPBlockDurationSeconds 0, 300 A positive violation threshold temporarily blocks an IP when IP filtering is enabled; zero disables automatic blocking.
EnableSecurityLogging true Emits logs when security checks reject or limit traffic.

The following properties are present in SecurityOptions but are not currently enforced by the core network paths: EnableHTTPAttackDetection, MaxHTTPHeaderSize, MaxHTTPHeaders, EnableSYNFloodDetection, MaxHalfOpenConnectionsPerIp, EnableRequestDeduplication, DeduplicationWindowSeconds, EnableSecurityMetrics, and MessageTimeoutSeconds. Setting them does not activate the named behavior. GetSecurityMetrics() reports counters for implemented protections regardless of EnableSecurityMetrics.

The lower-level RateLimiter, PerConnectionRateLimiter, DDoSDetector, SlowlorisDetector, IPBlocklist, and PayloadValidator classes can also be used directly. RequestDeduplicator hashes payloads and tracks repeated hashes in a time window, but it is not currently connected to NetworkServer message processing.

Configuration Reference

Configuration is shared by the client or server created from it. The defaults below are from the core package; separate transports use only the settings relevant to their transport.

Setting Purpose
Protocol, Host, Port Select TCP/UDP and the endpoint. The default protocol is TCP; the default endpoint is 127.0.0.1:8080.
ProtocolFactory Optional custom INetworkProtocol factory used by Configuration.GetProtocol(). It does not replace the transports in NetworkClient or NetworkServer.
MaxConnections Maximum server connection limit.
BufferSize, MAX_MESSAGE_SIZE I/O buffer and maximum accepted message size. The defaults are BufferSizeMaximum.Huge and MessageSizeMaximum.Default.
MessageFraming, Delimiter, LengthPrefixedLength, UseBigEndian TCP message framing and length-prefix format. Delimiter defaults to %; the default prefix length is 4 bytes and default byte order is little-endian.
EnableAutoReconnect, MaxReconnectAttempts Client reconnect policy. Auto-reconnect defaults on; a maximum of zero means no configured per-sequence attempt limit. Repeated retry sequences stop after the internal consecutive-failure cutoff.
ReconnectDelayInSeconds Public setting currently not read by the core reconnect loop; retries use its implemented backoff instead.
SSLMaxRetries, SSLRetryDelayInSeconds, UseExponentialBackoffForSslRetries, SSLRetryDelayMaxSeconds Connect/TLS retry policy. Zero retry count means no configured maximum. The exponential delay helper is used by the server handshake path; the TCP client currently uses the fixed delay.
SSLTimeoutInSeconds Public setting currently not read by the core connection paths. Use ConnectionTimeout and cancellation for actual connection timeout behavior.
EnableKeepAlive, KeepAliveTimeSeconds, KeepAliveIntervalSeconds, KeepAliveRetryCount TCP keep-alive behavior.
EnableHeartbeat, HeartbeatIntervalSeconds, DisconectOnMissedPong Application-level ping/pong heartbeat behavior.
ConnectionTimeout, ReadTimeoutSeconds, WriteTimeoutSeconds Connection and I/O timeouts.
Certificate, AdditionalCertificates, TrustedThumbprints, CheckCertificateRevocation, MutuallyAuthenticate, AllowTlsRenegotiation, IsSelfSignedEnabled TLS certificate and trust controls. UseSsl is derived from whether Certificate is set; AdditionalCertificates supplies chain certificates and TrustedThumbprints provides explicit thumbprint trust. Revocation checks and renegotiation are off by default. MutuallyAuthenticate enables client-certificate authentication. IsSelfSignedEnabled bypasses normal validation and is unsafe in production.
UseAesEncryption, AesPassword Optional AES payload encryption.
EnableNagle, EnableRST, EnableDualStack, EnableBroadcast EnableNagle controls TCP Nagle buffering; EnableRST configures reset-on-close; EnableDualStack enables IPv4/IPv6 server listeners where supported; EnableBroadcast enables UDP broadcast. All default to false.
EnableConnectionDebugLogs, EnablePingPongLogs, EnableSslDiagnostics Diagnostic logging options.
EnableHealthApi, HealthApiPort, HealthApiBindAddress Optional health/status listener. Port 0 asks the OS for an available port; the default bind address is loopback.
EnableAutoHtmlReports, HtmlReportOutputDirectory, HtmlReportIntervalSeconds Periodic socket diagnostic HTML reports.
EnableServerStatusPage, ServerStatusPageIntervalSeconds Periodic server status report.
IsRunningInContainer, DisableInternalCertificateCheck() Runtime/container detection and an option to disable the library's built-in trusted-thumbprint check. This does not make an untrusted certificate safe to accept.

Convenience methods UseContainerDefaults(), UseHighScaleProduction(), and UseDistributedProduction() adjust selected defaults. Review their values against your deployment rather than treating them as universal tuning profiles.

UseContainerDefaults() binds the primary endpoint and health listener to all interfaces. UseHighScaleProduction() raises the connection limit, disables verbose connection/ping logging, and adjusts TCP keep-alive intervals. UseDistributedProduction() changes the connection limit and socket options. These methods do not configure certificates, secrets, firewall rules, or application authorization.

Events and Monitoring

Client events

NetworkClient exposes OnConnected, OnDisconnected, OnDataReceived, OnNicknameSend, OnSslError, OnEncryptionError, OnGeneralError, OnSocketError, OnPingResponse, and OnPongResponse.

Server events

NetworkServer exposes OnConnected, OnConnectedWithNickname, OnDisconnected, OnDataReceived, OnClientMissing, OnSslError, OnEncryptionError, OnGeneralError, OnSocketError, OnClientPingResponse, and OnPongMissed.

OnConnected and OnDisconnected report lifecycle changes; nickname events report a nickname being sent or registered; OnDataReceived reports each payload delivered by the configured framing mode. Errors are separated by TLS, AES, socket, and general failures. Server OnClientMissing reports failed addressing, and ping/pong events report heartbeat responses or missed responses. Event handlers should return quickly; queue longer work elsewhere so receive processing is not delayed.

Both types expose byte/message counters, connection state, and a StatusPage for socket diagnostics. The server additionally provides ActiveConnections, TotalConnections, DroppedConnections, DroppedPackets, MessagesPerSecond, Uptime, GetStats(), and GetSecurityMetrics(). HealthApi is available on both types; configure EnableHealthApi and its bind address to enable the optional API. Server status reporting is controlled by EnableServerStatusPage.

Stats.MessagesPerSecond is the cumulative number of received messages divided by uptime, not a short-window throughput gauge. ConnectionEventArgs carries client ID, nickname, endpoint, timestamp, disconnect reason, exception, initiator, reason details, and diagnostic context. DataReceivedEventArgs carries raw bytes and metadata; StringData decodes those bytes as UTF-8 even when IsBinary is true. ErrorEventArgs carries the exception and message. Ping event args identify the peer and response time.

Disconnect reasons distinguish local/remote closure, timeout, TLS or encryption failure, missed pong, protocol error, buffer overflow, common socket failures such as reset/refused/unreachable, and server shutdown. ConnectionEventArgs.Determine maps common socket and transport exceptions to a reason. Inspect Exception and diagnostic context as well as the enum when handling disconnects.

The static NetworkClient.OnLog and NetworkServer.OnLog events publish library log messages. DEBUG_DATA_SEND and DEBUG_DATA_RECEIVED enable payload-level debug output on instances; avoid verbose payload logging for sensitive data or high-volume production traffic.

Health and diagnostic reports

When EnableHealthApi is enabled, the client or server starts a small HTTP listener. It accepts GET requests at /health and /status for JSON health/state, /dashboard for the built-in traffic dashboard, and / for the endpoint index. The default bind address is loopback; the listener does not provide authentication or HTTPS, so do not bind it to an untrusted network. When HealthApiPort is 0, read the selected port from HealthApi.Port after startup.

StatusPage is a bounded in-memory history of socket, general, and TLS errors. It exposes recent/all errors and filters by time, source, socket code, socket exception, or TLS error; it can also generate a periodic HTML report. ServerStatus generates a separate HTML snapshot of server connection counts, traffic counters, connected clients, and recent TLS errors. Both reports write files to HtmlReportOutputDirectory; configure permissions and storage retention for the host.

Utility Types

JSON stream processing

JsonDataProcessor<TData> accepts arbitrary byte or string chunks and keeps an incremental JSON parser per client name. It emits OnProcessMessage for complete JSON values deserialized to TData, and OnProcessTextMessage for non-JSON text between JSON values. OnError reports invalid input or parse failures. RemoveClient discards one parser context; idle contexts are periodically removed unless KeepIdleClients is true. MaxAllowedBufferSize limits parser buffering and IdleTimeout controls cleanup. Dispose the processor to stop its cleanup timer and release parser state.

Network monitoring

NetworkMonitor periodically pings a target host, stores a bounded history of samples, and raises sample, outage-detected, and outage-recovered events. GetHealthReport() summarizes reachability, uptime percentage, average/min/max latency, jitter, outage windows, and current system network-interface byte rates. Those byte-rate values describe active host interfaces, not traffic for a particular NetworkClient. StartAutoHtmlReport() periodically writes the health report as HTML. ICMP may be blocked or deprioritized even when the application's TCP/UDP endpoint is reachable.

Load and stress testing

LoadTester repeatedly creates core NetworkClient instances up to a target connection count, sends a fixed test message at the configured rate, logs progress, and closes its clients when the duration ends. RunAsync(duration, connectionRatePerSecond, messageRate) runs the workload; GetReport() returns connection, send-volume, error, and throughput fields. Use it against an explicitly authorized test server; the configured connection and send rates can consume substantial local and remote resources.

StressTest creates a fixed number of clients, sends a configured number of messages per client, records replies and per-client errors, and exposes a StressTestResult with summary and CSV export. StressTestRunner.RunQuickTestAsync provides a smaller convenience run. These tools exercise the core NetworkClient; they are not protocol-independent load generators.

Certificates and protocols

CertificateHelper loads certificates from supported files or the local certificate store and provides install/remove helpers. Do not use CertificateHelper.CheckCertificate for trust validation: its current callback accepts all server certificates. Use the normal Configuration certificate validation path and an explicit trust configuration instead.

ProtocolFactory can register named protocol factories, create by name or ProtocolType, query whether a name is registered, list registrations, and unregister custom registrations. The built-in TCP and UDP registrations cannot be removed. INetworkProtocol defines the transport lifecycle, send/receive, socket/stream access, and configuration hooks; custom implementations should return a fresh disposable instance and honor the hooks they support. IBroadcastConfigurableProtocol adds the optional UDP broadcast configuration hook.

TcpSeparators provides common delimiter byte sequences. Connection represents a server-side peer and exposes its ID, endpoint, nickname, times, byte counters, security flags, metadata dictionary, and connection state. Stats holds aggregate counts. DisconnectionDiagnostics, ConnectionLogger, and ConnectionLogManager provide disconnect-cause analysis and connection/error logging; SslHandshakeDiagnostics and SslMetrics expose TLS handshake stages and negotiated details.

AesKeyExchange contains the low-level AES key-exchange and payload encrypt/decrypt helpers used by the built-in encryption flow. StringHelper.GetTextBetweenTags extracts text between markers and SanitizeUsername normalizes a username. ConnectionTimeFormatter formats elapsed durations, while HandlingHelpers provides guarded event invocation, fire-and-forget task handling, and safe disposal helpers.

EonaCat.Connections provides TCP and UDP. The transports and integrations below are separate NuGet packages with their own entry-point types; installing one does not replace NetworkClient or NetworkServer automatically.

Package Client and server types Framework
EonaCat.Connections NetworkClient, NetworkServer (TCP/UDP) .NET Framework 4.8.1 and .NET 8
EonaCat.Connections.gRPC GrpcNetworkClient, GrpcNetworkServer .NET 8
EonaCat.Connections.Quic QuicNetworkClient, QuicNetworkServer .NET 8; preview-feature opt-in
EonaCat.Connections.REST RestNetworkClient, RestNetworkServer .NET 8
EonaCat.Connections.OpcUa OpcUaNetworkClient, OpcUaNetworkServer .NET 8

Install only the packages needed by the application:

dotnet add package EonaCat.Connections.gRPC
dotnet add package EonaCat.Connections.Quic
dotnet add package EonaCat.Connections.REST
dotnet add package EonaCat.Connections.OpcUa

gRPC

The gRPC integration provides a bidirectional streaming RPC. It supports text and byte payloads, nicknames, client events, per-client sends, broadcasts, optional heartbeat, automatic reconnect, statistics, and the optional health API. The server exposes an HTTP/2 endpoint and enforces MAX_MESSAGE_SIZE for received and sent gRPC messages. TLS 1.2/1.3 is enabled when a certificate is configured on the shared Configuration.

The ConnectorService.Connect RPC reads and writes ConnectorMessage values. DATA carries the application bytes in Data; NICKNAME carries a nickname in Text; PING and PONG are heartbeat controls; and DISCONNECT closes the stream. Heartbeat controls are exchanged when EnableHeartbeat is enabled. Applications normally use GrpcNetworkClient and GrpcNetworkServer rather than constructing these protobuf messages directly.

using EonaCat.Connections.Models;
using EonaCat.Connections.gRPC;

var serverConfig = new Configuration { Host = "0.0.0.0", Port = 5051 };
using var server = new GrpcNetworkServer(serverConfig);
server.OnDataReceived += async (_, message) =>
    await server.SendToClientAsync(message.ClientId, message.Data);
await server.StartAsync();

var clientConfig = new Configuration { Host = "127.0.0.1", Port = 5051 };
using var client = new GrpcNetworkClient(clientConfig);
client.OnDataReceived += (_, message) => Console.WriteLine(message.StringData);

if (await client.ConnectAsync())
{
    await client.SendAsync("Hello over gRPC");
}

Configure the same TLS certificate/trust expectations on both sides when securing the endpoint. As with the core client, configure certificate validation deliberately; IsSelfSignedEnabled disables normal certificate validation and is unsuitable for production.

QUIC

QUIC uses a TLS-protected connection with a bidirectional stream. The client and server provide connect, send, disconnect, lifecycle/data/error events, connection limits on the server, counters, and server broadcasts. The server requires Configuration.Certificate; configure the client to trust that certificate. QUIC support depends on the operating system and runtime, and the implementation is annotated as using preview features. The current client expects Configuration.Host to be an IP address because it parses the value directly.

The QUIC stream is byte-oriented: a receive event reflects a stream read, not an application message boundary. Add application framing when the protocol needs discrete messages. Client and server must use the same PROTOCOL_CONNECTION_NAME for ALPN negotiation; inbound stream limits and default stream/connection close error codes are also configurable on the QUIC types.

using EonaCat.Connections.Models;
using EonaCat.Connections.Quic;

var serverConfig = new Configuration
{
    Host = "0.0.0.0",
    Port = 5052,
    Certificate = serverCertificate
};
using var server = new QuicNetworkServer(serverConfig);
server.OnDataReceived += async (_, message) =>
    await server.SendToClientAsync(message.ClientId, message.Data);
await server.StartAsync();

var clientConfig = new Configuration { Host = "127.0.0.1", Port = 5052 };
await using var client = new QuicNetworkClient(clientConfig);
if (await client.ConnectAsync())
{
    await client.SendAsync("Hello over QUIC");
}

QUIC is a separate API, not a ProtocolType option for NetworkClient or NetworkServer. Confirm QuicConnection.IsSupported on the deployment platform and enable preview features in applications that consume the package.

REST and webhooks

The REST package hosts an HTTP API and represents each connected client with a generated client ID. RestNetworkClient.ConnectAsync() registers the client; it sends data using HTTP POST and receives queued server messages by polling. The server supports these routes:

Method and route Purpose
POST /api/connect Creates a client record and returns its generated clientId; returns 429 when the connection limit is reached.
POST /api/disconnect Disconnects the client named by clientId.
POST /api/send Sends a client's payload to the server-side OnDataReceived event. Clients send payloads as Base64 in the data field.
GET /api/poll/{clientId} Drains that client's pending server messages and returns them as Base64 strings in messages.
POST /api/broadcast Broadcasts data to all clients except the optional sender clientId.
POST /api/nickname Sets the supplied nickname on the identified client.
GET /api/ping/{clientId} Updates activity/pong time and returns a pong response.
POST /api/webhooks/register Sets the client's callback URL used for server-to-client message delivery.
POST /api/webhooks/unregister Clears the client's callback URL so queued polling is used again.
POST /api/aes/init/{clientId} Initializes a client's AES state from supplied salt/IV when AES is enabled on the server.

REST client/server also expose lifecycle and data events, counters, connection limits, optional TLS, and optional AES payload encryption. The routes do not implement authentication or authorization; put the server behind an authenticated gateway or restrict network access before exposing it beyond a trusted network.

using EonaCat.Connections.Models;
using EonaCat.Connections.REST;

var serverConfig = new Configuration { Host = "0.0.0.0", Port = 5053 };
using var server = new RestNetworkServer(serverConfig);
server.OnDataReceived += async (_, message) =>
    await server.SendToClientAsync(message.ClientId, $"Echo: {message.StringData}");
await server.StartAsync();

var clientConfig = new Configuration { Host = "127.0.0.1", Port = 5053 };
using var client = new RestNetworkClient(clientConfig);
client.OnDataReceived += (_, message) => Console.WriteLine(message.StringData);
if (await client.ConnectAsync())
{
    await client.SendAsync("Hello over REST");
}

For callback delivery, RestNetworkServer.Webhooks registers event names and destination URLs, for example connected, data_received, and broadcast. A REST client can also start a local webhook listener with StartWebhookListenerAsync(port) and register it with RegisterWebhookAsync; the built-in listener binds to loopback, so it is intended for local callback delivery unless the application provides another reachable endpoint. Webhook delivery is outbound HTTP POST, sequential, best-effort, and has no retry; outbound failures are swallowed. Protect and monitor the callback targets like any other outbound integration.

REST provides HTTP request/response semantics rather than TCP-style stream delivery: clients poll for messages when webhooks are not used, so account for polling latency and HTTP overhead when choosing it.

OPC UA

The OPC UA package is a separate industrial interoperability API, not a byte-message transport. OpcUaNetworkServer publishes a configured address space under an EonaCat folder; register variables and callable methods before starting it. Variables have scalar data types, initial values, access levels, and optional descriptions. TrySetValue updates a registered variable and raises ValueChanged; client writes to a writable variable also raise that event. Methods declare typed input/output arguments and invoke the supplied handler when called.

OpcUaNetworkClient connects to an endpoint, browses hierarchical references from ObjectsFolder, reads and writes variable values, calls methods, and subscribes to monitored value changes. Subscriptions default to 1000 ms publishing/sampling intervals, queue up to 10 values per item, and discard the oldest queued value when full. The client can reconnect after a session keep-alive failure, and both client and server expose lifecycle/error events.

using EonaCat.Connections.OpcUa.Configuration;
using EonaCat.Connections.OpcUa.Models;
using EonaCat.Connections.OpcUa.Server;
using Opc.Ua;

var server = new OpcUaNetworkServer(new OpcUaServerOptions
{
    BaseAddress = "opc.tcp://localhost:4840/EonaCat/Connector",
    NamespaceUri = "urn:example:machine"
});
server.AddVariable(new OpcUaNodeDefinition(
    Identifier: "Temperature",
    DisplayName: "Temperature",
    DataType: DataTypeIds.Double,
    InitialValue: 20.0));
server.AddMethod(new OpcUaMethodDefinition(
    Identifier: "Add",
    DisplayName: "Add",
    InputArguments:
    [
        new OpcUaMethodArgument("left", DataTypeIds.Double),
        new OpcUaMethodArgument("right", DataTypeIds.Double)
    ],
    OutputArguments: [new OpcUaMethodArgument("sum", DataTypeIds.Double)],
    Handler: arguments => new object?[] { (double)arguments[0]! + (double)arguments[1]! }));
await server.StartAsync();

// Update a published variable by its registered identifier.
server.TrySetValue("Temperature", 21.5);
using EonaCat.Connections.OpcUa.Client;
using EonaCat.Connections.OpcUa.Configuration;

await using var client = new OpcUaNetworkClient(new OpcUaClientOptions
{
    EndpointUrl = "opc.tcp://localhost:4840/EonaCat/Connector"
});

if (await client.ConnectAsync())
{
    const string namespaceUri = "urn:example:machine";
    var temperatureNode = client.GetNodeId(namespaceUri, "Temperature");
    Console.WriteLine((await client.ReadAsync(temperatureNode)).Value);
    await client.WriteAsync(temperatureNode, 22.0);

    var sum = await client.CallAsync(
        client.GetNodeId(namespaceUri, "EonaCat"),
        client.GetNodeId(namespaceUri, "Add"),
        new object?[] { 2.0, 3.0 });
    Console.WriteLine(sum[0]);

    await using var subscription = await client.SubscribeAsync(
        new[] { temperatureNode },
        (_, change) => Console.WriteLine($"Temperature: {change.Value}"));
}

The corresponding client uses OpcUaClientOptions.EndpointUrl and ConnectAsync(). Resolve a node using GetNodeId(namespaceUri, identifier) or browse from ObjectsFolder, then use ReadAsync, WriteAsync, CallAsync, or SubscribeAsync. CallAsync takes both the containing object node ID and method node ID plus ordered input values. Dispose the returned subscription when it is no longer needed. Server security defaults enable a secure endpoint and also allow an unsecured endpoint; client security defaults on, untrusted certificates are not automatically accepted, and revocation checking is on. Server options control endpoint/namespace, certificate policy, session count, and subscription count. Client options control endpoint security, optional username/password identity, certificate checks, operation/session timeouts, and reconnect behavior. Disable unsecured endpoints unless required and configure trust before exposing an OPC UA endpoint.

All transports and integrations should be stopped and disposed explicitly. For TCP, UDP, gRPC, and REST servers, StartAsync() starts listening and returns; await StopAsync() during graceful shutdown. QUIC and OPC UA have their own client/server lifecycle methods as described above.

Resource Cleanup

Dispose clients and servers when finished. On servers, use await StopAsync() when shutdown should complete before the application exits; Stop() is a fire-and-forget convenience method. Configuration implements IDisposable and disposes its configured certificate, so avoid sharing a certificate-owning configuration across components with unrelated lifetimes.

License

See the LICENSE file.

S
Description
EonaCat.Connections
Readme Apache-2.0
1 MiB
0 Stars 1 Watchers 0 Forks
Languages
C# 97.8%
HTML 2.1%