Skip to content

07. Network

ogoun edited this page Apr 23, 2026 · 1 revision

Network

ZeroLevel ships a full duplex TCP stack: message / request-response / keep-alive framing, an adaptive buffer manager, request/response correlation, and a pluggable discovery client.

The public API surface is deliberately narrow — for most code you interact with two things:

  1. UseHost(...) on a BaseZeroService — expose a TCP endpoint.
  2. Exchange.GetConnection(endpoint) — obtain an IClient to talk to another endpoint.

Hosting a server

Inside any BaseZeroService.StartAction you can call UseHost() to bind a TCP listener:

protected override void StartAction()
{
    var router = UseHost(8800);              // bind on 0.0.0.0:8800
    // router = UseHost();                    // OS-chosen port
    // router = UseHost(IPEndPoint.Parse(...));
    // router = UseHostV6();                  // IPv6

    router.RegisterMessageHandler<Ping>((client, msg) =>
        Log.Info($"ping from {client.EndPoint}"));

    router.RegisterRequester<PingRequest, PongResponse>((client, req) =>
        new PongResponse { Ts = DateTime.UtcNow });

    router.RegisterInbox<Ping>("metrics", (client, msg) =>
        Log.Info($"metrics ping from {client.EndPoint}"));
}

IRouter is the server-side contract. The main methods:

  • RegisterMessageHandler<T>(Action<IClient, T> handler) — fire-and-forget receiver.
  • RegisterRequester<TReq, TResp>(Func<IClient, TReq, TResp> handler) — synchronous reply.
  • RegisterInbox<T>(string inbox, Action<IClient, T> handler) — named message channel.
  • RegisterInboxRequester<TReq, TResp>(string inbox, ...) — named request channel.

Built-in inbox names (reserved by the protocol): __message_inbox__, __request_inbox__, __discovery__.

Client side

using ZeroLevel.Network;

var exchange = Injector.Default.Resolve<IExchange>();    // obtained from the host
var client   = exchange.GetConnection("127.0.0.1:8800");

// one-way message
client.Send(new Ping { Ts = DateTime.UtcNow });

// request / response (timeout: 30s by default)
var pong = await client.Request<PingRequest, PongResponse>(new PingRequest());

// named inbox
client.Send("metrics", new MetricsReport());
var answer = await client.Request<RouteRequest, RouteResponse>("routing", new RouteRequest());

IExchange is the entry point for outbound connections. It is owned by the service and re-uses the underlying TCP sockets — getting the same endpoint twice returns the same IClient.

Exchange itself is internal sealed — there is no user-provided implementation. Your host is always the one obtained through UseHost() / BaseZeroService.

Protocol, frames, limits

The protocol is binary duplex TCP. Every frame starts with a single-byte magic number:

Magic Frame
153 Message — fire & forget.
155 Request — expects a matching response.
185 Response — reply to a prior request (matched by RequestId).
187 Keep-alive.

Headers:

  • Message: magic (1) + size (int32) + checksum (1) + payload → 6-byte header.
  • Request / Response: magic (1) + size (int32) + RequestId (int32) + checksum (1) + payload → 10-byte header.
  • Keep-alive: fixed 9 bytes.

Limits and timings:

Limit Value
Max payload 32 MB
Outbound queue 256 frames
Request timeout 30 s
TCP keep-alive (idle, interval) 10 s / 5 s

Checksum. The "checksum" byte is a chained XOR over payload bytes: data[i] ^= data[i-1], seeded with the header checksum byte. This is corruption detection, not cryptographic integrity — cheap to compute, good enough for catching line-noise type errors.

Frame parser. Inbound bytes feed a state machine (FrameParser) with states WaitNew → WaitSize → WaitIdentity → Proceeding. Parser state is per-connection.

Threading model

The network stack is built on explicit Threads, not async/await:

  • One receive thread per connection.
  • One send thread per connection (drains the outbound queue).
  • Synchronization via ManualResetEventSlim, ConcurrentQueue<T>, Interlocked.

IAsyncBinarySerializable exists but is not integrated into the network path today — the wire codec is synchronous.

Discovery

Opt-in discovery lets services find each other via a central hub.

Bootstrap.Startup<MyService>(args)
    .UseDiscovery()                          // default hub location from config
    .UseDiscovery("http://discovery:4300")    // explicit URL
    .UseDiscovery(IPEndPoint.Parse("10.0.0.1:4300"));

Contracts:

  • IDiscoveryClient — register/lookup services.
  • IServiceRoutesStorage — the storage backing discovery (pluggable).
  • ZeroServiceInfo — name/key/version/group/type tuple that identifies a service.

File transfer

The ZeroLevel.Services.Network.FileTransfer/ namespace adds chunked file upload/download built on top of the same TCP stack — see FileSender / FileReceiver.

Tips

  • UseHost() implicitly starts the listener in a background thread. Call it once per service from StartAction.
  • Prefer named inboxes (RegisterInbox<T>("name", ...)) when you have more than one consumer for the same message type — they give you clear per-channel routing.
  • Keep request handlers short. They run on the receive thread. Offload heavy work to a scheduler (Sheduller) or a background task.
  • When targeting stable long-lived connections (e.g. a data replicator), tune TCP keep-alive via the OS — the library already sets sensible (10s, 5s) defaults but the OS may cap them.
  • Large payloads: up to 32 MB per frame. Chunk manually (or use FileTransfer) for bigger transfers.

Clone this wiki locally