diff --git a/docs/cultnet-transport-parity.md b/docs/cultnet-transport-parity.md
index 48a0e2b6..3073a01d 100644
--- a/docs/cultnet-transport-parity.md
+++ b/docs/cultnet-transport-parity.md
@@ -137,6 +137,10 @@ lets the runtimes stop guessing what kind of pipe a peer is offering.
Current progress:
- Steps 1-3 are live in C#, TypeScript, Rust, and Python.
+- C# now has the shared `tcp_framed` transport profile helper plus a
+ `TcpFramedTransportConnection` with schema-channel `SendAsync`,
+ `ReceiveAsync`, and transfer stats. The C# interop peer advertises and uses
+ that shared port instead of owning raw TCP frame I/O directly.
- TypeScript has the first narrow transport connection port:
`TcpFramedTransportConnection` owns length-prefixed frame delivery, exposes
frame/close/error events, `send(channel, payload)`, `close`, and transfer
@@ -150,7 +154,7 @@ Current progress:
`TcpFramedTransportConnection` with schema-channel `send`, `receive`, and
transfer stats. The Rust interop peer advertises and uses that shared port
instead of owning raw TCP frame I/O directly.
-- The remaining parity work is to add equivalent ports to C# and Kotlin, deepen
+- The remaining parity work is to add the equivalent port to Kotlin, deepen
Python's server-side use of its port, and move each runtime's existing
TCP/LiteNetLib/WebSocket bodies behind those ports before implementing
`rudp`.
diff --git a/src/GameCult.Networking/CultNetTransport.cs b/src/GameCult.Networking/CultNetTransport.cs
new file mode 100644
index 00000000..cfafa6b3
--- /dev/null
+++ b/src/GameCult.Networking/CultNetTransport.cs
@@ -0,0 +1,213 @@
+using System;
+using System.Buffers.Binary;
+using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace GameCult.Networking
+{
+ ///
+ /// Transfer counters for a CultNet transport connection.
+ ///
+ public sealed class CultNetTransportStats
+ {
+ ///
+ /// Gets the number of payload frames sent through the connection.
+ ///
+ public long FramesSent { get; internal set; }
+ ///
+ /// Gets the number of payload frames received through the connection.
+ ///
+ public long FramesReceived { get; internal set; }
+ ///
+ /// Gets the number of bytes sent, including transport framing.
+ ///
+ public long BytesSent { get; internal set; }
+ ///
+ /// Gets the number of bytes received, including transport framing.
+ ///
+ public long BytesReceived { get; internal set; }
+
+ internal CultNetTransportStats Snapshot()
+ {
+ return new CultNetTransportStats
+ {
+ FramesSent = FramesSent,
+ FramesReceived = FramesReceived,
+ BytesSent = BytesSent,
+ BytesReceived = BytesReceived
+ };
+ }
+ }
+
+ ///
+ /// Payload delivered by a CultNet transport connection.
+ ///
+ public sealed class CultNetTransportFrame
+ {
+ ///
+ /// Gets or sets the logical transport channel.
+ ///
+ public string ChannelId { get; set; } = "schema";
+ ///
+ /// Gets or sets the raw payload bytes carried by the frame.
+ ///
+ public byte[] Payload { get; set; } = Array.Empty();
+ }
+
+ ///
+ /// Options for creating a TCP framed transport profile.
+ ///
+ public sealed class TcpFramedTransportProfileOptions
+ {
+ ///
+ /// Gets or sets the advertised transport id.
+ ///
+ public string TransportId { get; set; } = "tcp-framed";
+ ///
+ /// Gets or sets the advertised host.
+ ///
+ public string? Host { get; set; }
+ ///
+ /// Gets or sets the advertised port.
+ ///
+ public int? Port { get; set; }
+ ///
+ /// Gets or sets the maximum payload size for the schema channel.
+ ///
+ public int? MaxPayloadBytes { get; set; }
+ ///
+ /// Gets or sets the maximum fragment size for the schema channel.
+ ///
+ public int? MaxFragmentBytes { get; set; }
+ }
+
+ ///
+ /// Helpers for creating CultNet transport profile documents.
+ ///
+ public static class CultNetTransportProfiles
+ {
+ ///
+ /// Creates a profile for the current length-prefixed TCP schema lane.
+ ///
+ public static CultNetTransportProfile CreateTcpFramed(
+ string runtimeId,
+ TcpFramedTransportProfileOptions? options = null)
+ {
+ if (string.IsNullOrWhiteSpace(runtimeId)) throw new ArgumentException("Runtime id is required.", nameof(runtimeId));
+ options ??= new TcpFramedTransportProfileOptions();
+ return new CultNetTransportProfile
+ {
+ RuntimeId = runtimeId,
+ Transports =
+ [
+ new CultNetTransportDescriptor
+ {
+ TransportId = string.IsNullOrWhiteSpace(options.TransportId)
+ ? "tcp-framed"
+ : options.TransportId,
+ Protocol = "tcp_framed",
+ Host = options.Host,
+ Port = options.Port,
+ WireContracts = [CultNetWireContracts.SchemaV0],
+ Channels =
+ [
+ new CultNetTransportChannel
+ {
+ ChannelId = "schema",
+ Delivery = "reliable",
+ Ordering = "ordered",
+ MaxPayloadBytes = options.MaxPayloadBytes,
+ MaxFragmentBytes = options.MaxFragmentBytes
+ }
+ ]
+ }
+ ]
+ };
+ }
+ }
+
+ ///
+ /// Transport connection for the current TCP length-prefixed CultNet schema lane.
+ ///
+ public sealed class TcpFramedTransportConnection
+ {
+ private const int HeaderBytes = 4;
+ private readonly Stream _stream;
+ private readonly CultNetTransportStats _stats = new CultNetTransportStats();
+
+ ///
+ /// Initializes a TCP framed transport over an existing stream.
+ ///
+ public TcpFramedTransportConnection(Stream stream, CultNetTransportProfile profile)
+ {
+ _stream = stream ?? throw new ArgumentNullException(nameof(stream));
+ Profile = profile ?? throw new ArgumentNullException(nameof(profile));
+ }
+
+ ///
+ /// Gets the profile this connection implements.
+ ///
+ public CultNetTransportProfile Profile { get; }
+
+ ///
+ /// Gets a snapshot of the current transfer counters.
+ ///
+ public CultNetTransportStats Stats => _stats.Snapshot();
+
+ ///
+ /// Sends a schema-channel payload.
+ ///
+ public async Task SendAsync(string channelId, byte[] payload, CancellationToken cancellationToken = default)
+ {
+ if (!string.Equals(channelId, "schema", StringComparison.Ordinal))
+ {
+ throw new InvalidOperationException($"tcp_framed transport only supports the schema channel, got \"{channelId}\".");
+ }
+
+ if (payload == null) throw new ArgumentNullException(nameof(payload));
+ var header = new byte[HeaderBytes];
+ BinaryPrimitives.WriteUInt32BigEndian(header, checked((uint)payload.Length));
+ await _stream.WriteAsync(header, cancellationToken).ConfigureAwait(false);
+ await _stream.WriteAsync(payload, cancellationToken).ConfigureAwait(false);
+ await _stream.FlushAsync(cancellationToken).ConfigureAwait(false);
+ _stats.BytesSent += HeaderBytes + payload.Length;
+ _stats.FramesSent++;
+ }
+
+ ///
+ /// Receives the next schema-channel payload.
+ ///
+ public async Task ReceiveAsync(CancellationToken cancellationToken = default)
+ {
+ var header = new byte[HeaderBytes];
+ await ReadExactlyAsync(header, cancellationToken).ConfigureAwait(false);
+ var payloadLength = checked((int)BinaryPrimitives.ReadUInt32BigEndian(header));
+ var payload = new byte[payloadLength];
+ await ReadExactlyAsync(payload, cancellationToken).ConfigureAwait(false);
+ _stats.BytesReceived += HeaderBytes + payloadLength;
+ _stats.FramesReceived++;
+ return new CultNetTransportFrame
+ {
+ ChannelId = "schema",
+ Payload = payload
+ };
+ }
+
+ private async Task ReadExactlyAsync(byte[] buffer, CancellationToken cancellationToken)
+ {
+ var offset = 0;
+ while (offset < buffer.Length)
+ {
+ var read = await _stream.ReadAsync(buffer.AsMemory(offset, buffer.Length - offset), cancellationToken)
+ .ConfigureAwait(false);
+ if (read == 0)
+ {
+ throw new EndOfStreamException();
+ }
+
+ offset += read;
+ }
+ }
+ }
+}
diff --git a/tests/GameCult.Networking.InteropPeer/Program.cs b/tests/GameCult.Networking.InteropPeer/Program.cs
index ad9c05a9..13e7d5f1 100644
--- a/tests/GameCult.Networking.InteropPeer/Program.cs
+++ b/tests/GameCult.Networking.InteropPeer/Program.cs
@@ -1,5 +1,4 @@
using System;
-using System.Buffers.Binary;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
@@ -183,8 +182,11 @@ static async Task DialAsync(DialConfig config)
using var client = new TcpClient();
await client.ConnectAsync(config.TargetHost, config.TargetPort);
using var stream = client.GetStream();
+ var transport = new TcpFramedTransportConnection(
+ stream,
+ CreateTcpFramedTransportProfile(config.RuntimeId, config.TargetHost, config.TargetPort));
- await SendMessageAsync(stream, new CultNetHelloMessage
+ await SendMessageAsync(transport, new CultNetHelloMessage
{
RuntimeId = config.RuntimeId,
RuntimeKind = config.RuntimeKind,
@@ -196,24 +198,24 @@ static async Task DialAsync(DialConfig config)
SupportedMessageVersions = [InteropPeerShared.InteropSchemaVersion],
SupportsSchemaCatalog = true
});
- var remoteHello = await ExpectMessageAsync(stream, CultNetSchemaVersions.Hello);
+ var remoteHello = await ExpectMessageAsync(transport, CultNetSchemaVersions.Hello);
- await SendMessageAsync(stream, new CultNetSchemaCatalogRequestMessage
+ await SendMessageAsync(transport, new CultNetSchemaCatalogRequestMessage
{
MessageId = $"{config.RuntimeId}-catalog",
IncludeSchemaJson = true,
SchemaIds = [schemaRegistration.SchemaId],
Kinds = ["document_payload"]
});
- var catalog = await ExpectMessageAsync(stream, CultNetSchemaVersions.SchemaCatalogResponse);
+ var catalog = await ExpectMessageAsync(transport, CultNetSchemaVersions.SchemaCatalogResponse);
- await SendMessageAsync(stream, new CultNetSnapshotRequestMessage
+ await SendMessageAsync(transport, new CultNetSnapshotRequestMessage
{
MessageId = $"{config.RuntimeId}-snapshot",
SchemaIds = [schemaRegistration.SchemaId],
RecordKeys = [$"note:{remoteHello.RuntimeId}"]
});
- var snapshot = await ExpectMessageAsync(stream, CultNetSchemaVersions.SnapshotResponseRaw);
+ var snapshot = await ExpectMessageAsync(transport, CultNetSchemaVersions.SnapshotResponseRaw);
await documentRegistry.ApplyRawSnapshotResponseAsync(cache, snapshot);
var note = cache.AllEntries
@@ -224,8 +226,8 @@ static async Task DialAsync(DialConfig config)
string.Equals(schema.SchemaId, schemaRegistration.SchemaId, StringComparison.Ordinal) &&
string.Equals(schema.DocumentType, InteropPeerShared.InteropDocumentType, StringComparison.Ordinal));
- var mutation = await MutateRemoteNoteAsync(stream, cache, documentRegistry, config.RuntimeId, note);
- var fireReceipt = await FireRemoteWeaponAsync(stream, cache, documentRegistry, config.RuntimeId, remoteHello.RuntimeId);
+ var mutation = await MutateRemoteNoteAsync(transport, cache, documentRegistry, config.RuntimeId, note);
+ var fireReceipt = await FireRemoteWeaponAsync(transport, cache, documentRegistry, config.RuntimeId, remoteHello.RuntimeId);
WriteJsonLine(new
{
@@ -261,7 +263,7 @@ static async Task DialAsync(DialConfig config)
}
static async Task