Add C# RUDP socket transport

This commit is contained in:
Meta Vens 2026-06-14 23:32:24 +01:00
commit 1ef6c672d4
3 changed files with 362 additions and 7 deletions

View file

@ -24,7 +24,7 @@ CultNet owns cross-runtime transport semantics:
| Runtime | Current data transport | Discovery | Transport authority today |
| --- | --- | --- | --- |
| C# `GameCult.Networking` | LiteNetLib UDP `NetManager` / `NetPeer`; sends legacy union messages and schema-v0 messages with `DeliveryMethod.ReliableOrdered` | LiteNetLib connection requests and app-level peer/catalog surfaces | C# owns the production-shaped realtime semantics |
| C# `GameCult.Networking` | LiteNetLib UDP `NetManager` / `NetPeer`; sends legacy union messages and schema-v0 messages with `DeliveryMethod.ReliableOrdered`; single-peer RUDP socket transport exists in the library | LiteNetLib connection requests and app-level peer/catalog surfaces | Production LiteNetLib path plus UDP socket binding for the shared RUDP reliability owner |
| C# interop peer | TCP stream with 4-byte length-prefixed MessagePack frames | UDP multicast probe/announce | Test harness only |
| TypeScript `cultnet-ts` | `CultNetPeer` over any Node `Duplex`, TCP-framed transport, or single-peer RUDP socket transport; interop uses TCP | UDP multicast probe/announce in the interop peer | First UDP socket binding for the shared RUDP reliability owner |
| Rust `cultnet-rs` | Interop example uses TCP length-prefixed MessagePack frames; single-peer RUDP socket transport exists in the library | UDP multicast probe/announce | UDP socket binding for the shared RUDP reliability owner |
@ -165,16 +165,15 @@ Current progress:
ack/ack-mask accounting, reliable resend scheduling, duplicate suppression,
and reliable ordered channel delivery. It is in-memory and socket-free so the
behavior can be tested before any runtime binds it to UDP I/O.
- TypeScript, Rust, and Python now have socket-backed RUDP transport
- C#, TypeScript, Rust, and Python now have socket-backed RUDP transport
connections that bind a single UDP peer to the shared RUDP session. TypeScript
emits the same `frame` events as the TCP-framed transport and can carry
`CultNetPeer` schema messages over reliable ordered `schema` frames; Rust and
Python expose the same transport frame/stats shape through synchronous socket
polling.
`CultNetPeer` schema messages over reliable ordered `schema` frames; C#,
Rust, and Python expose the same transport frame/stats shape through
synchronous socket polling.
- 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, then bind the shared RUDP
reliability state machine to UDP sockets in C#.
TCP/LiteNetLib/WebSocket bodies behind those ports.
## RUDP Packet Contract V0

View file

@ -3,6 +3,8 @@ using System.Buffers.Binary;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
@ -486,6 +488,68 @@ namespace GameCult.Networking
public long NowMs { get; set; }
}
/// <summary>
/// Role for a single-peer CultNet RUDP socket transport.
/// </summary>
public enum CultNetRudpSocketMode
{
/// <summary>
/// Initiates the connect packet.
/// </summary>
Client,
/// <summary>
/// Accepts the first connect packet from a remote endpoint.
/// </summary>
Server
}
/// <summary>
/// Options for binding a CultNet RUDP session to a UDP socket.
/// </summary>
public sealed class CultNetRudpSocketTransportOptions
{
/// <summary>
/// Gets or sets the runtime id advertised by this transport.
/// </summary>
public string RuntimeId { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the bound UDP socket.
/// </summary>
public Socket Socket { get; set; } = null!;
/// <summary>
/// Gets or sets whether this side initiates or accepts the handshake.
/// </summary>
public CultNetRudpSocketMode Mode { get; set; }
/// <summary>
/// Gets or sets the expected remote endpoint. Servers may leave this unset until the first connect packet.
/// </summary>
public EndPoint? RemoteEndPoint { get; set; }
/// <summary>
/// Gets or sets the RUDP connection/session binding id.
/// </summary>
public uint ConnectionId { get; set; }
/// <summary>
/// Gets or sets the first local packet sequence.
/// </summary>
public uint InitialSequence { get; set; } = 1;
/// <summary>
/// Gets or sets the resend delay in milliseconds.
/// </summary>
public long ResendDelayMs { get; set; } = 250;
/// <summary>
/// Gets or sets the advertised transport id.
/// </summary>
public string TransportId { get; set; } = "rudp";
/// <summary>
/// Gets or sets the maximum payload size for RUDP channels.
/// </summary>
public int? MaxPayloadBytes { get; set; }
/// <summary>
/// Gets or sets the maximum fragment size for RUDP channels.
/// </summary>
public int? MaxFragmentBytes { get; set; }
}
/// <summary>
/// Socket-free reliability state machine for CultNet RUDP.
/// </summary>
@ -821,6 +885,205 @@ namespace GameCult.Networking
}
}
/// <summary>
/// Single-peer UDP socket binding for the CultNet RUDP reliability session.
/// </summary>
public sealed class CultNetRudpSocketTransportConnection : IDisposable
{
private readonly Socket _socket;
private readonly CultNetRudpSession _session;
private readonly CultNetRudpSocketMode _mode;
private readonly CultNetTransportStats _stats = new CultNetTransportStats();
private readonly Queue<CultNetTransportFrame> _deliveredFrames = new Queue<CultNetTransportFrame>();
private EndPoint? _remoteEndPoint;
private bool _disposed;
/// <summary>
/// Initializes a UDP socket binding around a CultNet RUDP session.
/// </summary>
public CultNetRudpSocketTransportConnection(CultNetRudpSocketTransportOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
if (string.IsNullOrWhiteSpace(options.RuntimeId)) throw new ArgumentException("Runtime id is required.", nameof(options));
_socket = options.Socket ?? throw new ArgumentNullException(nameof(options.Socket));
_mode = options.Mode;
_remoteEndPoint = options.RemoteEndPoint;
_session = new CultNetRudpSession(new CultNetRudpSessionOptions
{
ConnectionId = options.ConnectionId,
InitialSequence = options.InitialSequence,
ResendDelayMs = options.ResendDelayMs
});
var local = _socket.LocalEndPoint as IPEndPoint;
Profile = CultNetTransportProfiles.CreateRudp(
options.RuntimeId,
new RudpTransportProfileOptions
{
TransportId = options.TransportId,
Host = local?.Address.ToString(),
Port = local?.Port,
MaxPayloadBytes = options.MaxPayloadBytes,
MaxFragmentBytes = options.MaxFragmentBytes
});
}
/// <summary>
/// Gets the profile this connection implements.
/// </summary>
public CultNetTransportProfile Profile { get; }
/// <summary>
/// Gets whether the RUDP handshake has completed.
/// </summary>
public bool Connected => _session.Connected;
/// <summary>
/// Gets a snapshot of the current transfer counters.
/// </summary>
public CultNetTransportStats Stats => _stats.Snapshot();
/// <summary>
/// Sends the client connect packet.
/// </summary>
public void Connect(byte[]? payload = null)
{
if (_mode != CultNetRudpSocketMode.Client)
{
throw new InvalidOperationException("Only a client RUDP socket transport can initiate connect.");
}
SendPacket(_session.CreateConnect(NowMs(), payload ?? Array.Empty<byte>()));
}
/// <summary>
/// Sends a logical transport frame through the RUDP session.
/// </summary>
public void Send(string channelId, byte[] payload)
{
var packet = _session.Send(channelId, payload, ChannelSendOptions(channelId));
SendPacket(packet);
_stats.FramesSent++;
}
/// <summary>
/// Polls the UDP socket once and returns the next delivered transport frame if one is available.
/// </summary>
public CultNetTransportFrame? ReceiveOnce()
{
if (_deliveredFrames.Count > 0)
{
return _deliveredFrames.Dequeue();
}
var buffer = new byte[65535];
EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
int received;
try
{
received = _socket.ReceiveFrom(buffer, ref remote);
}
catch (SocketException error) when (
error.SocketErrorCode == SocketError.WouldBlock ||
error.SocketErrorCode == SocketError.TimedOut)
{
return null;
}
_stats.BytesReceived += received;
if (_remoteEndPoint == null)
{
_remoteEndPoint = remote;
}
else if (!_remoteEndPoint.Equals(remote))
{
return null;
}
var wire = new byte[received];
Array.Copy(buffer, wire, received);
var packet = CultNetRudpPacketCodec.Decode(wire);
if (_mode == CultNetRudpSocketMode.Server && packet.PacketType == CultNetRudpPacketType.Connect)
{
SendPacket(_session.AcceptConnect(packet, NowMs()));
return null;
}
var result = _session.Receive(packet, NowMs());
if (result.Reply != null)
{
SendPacket(result.Reply);
}
foreach (var frame in result.Delivered)
{
_deliveredFrames.Enqueue(new CultNetTransportFrame
{
ChannelId = frame.ChannelId,
Payload = frame.Payload
});
_stats.FramesReceived++;
}
var delivered = _deliveredFrames.Count > 0 ? _deliveredFrames.Dequeue() : null;
if (packet.PacketType == CultNetRudpPacketType.Accept || delivered != null)
{
SendPacket(_session.CreateAck());
}
return delivered;
}
/// <summary>
/// Sends any reliable packets whose resend timers are due.
/// </summary>
public void PollResends()
{
foreach (var packet in _session.DueResends(NowMs()))
{
SendPacket(packet);
}
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_socket.Dispose();
}
private void SendPacket(CultNetRudpPacket packet)
{
if (_remoteEndPoint == null)
{
throw new InvalidOperationException("RUDP socket transport does not have a remote endpoint.");
}
var wire = CultNetRudpPacketCodec.Encode(packet);
var sent = _socket.SendTo(wire, _remoteEndPoint);
_stats.BytesSent += sent;
}
private static CultNetRudpSendOptions ChannelSendOptions(string channelId)
{
return string.Equals(channelId, "schema", StringComparison.Ordinal)
? new CultNetRudpSendOptions { Reliable = true, Ordered = true, NowMs = NowMs() }
: string.Equals(channelId, "latest", StringComparison.Ordinal)
? new CultNetRudpSendOptions { Sequenced = true, NowMs = NowMs() }
: new CultNetRudpSendOptions { NowMs = NowMs() };
}
private static long NowMs()
{
return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}
}
/// <summary>
/// Transport connection for the current TCP length-prefixed CultNet schema lane.
/// </summary>

View file

@ -3,6 +3,8 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
@ -19,6 +21,51 @@ namespace GameCult.Networking.Tests
private static readonly ServerSecurityOptions DevelopmentServerSecurity = ServerSecurityOptions.Development();
private static readonly ClientSecurityOptions DevelopmentClientSecurity = ClientSecurityOptions.Development();
private static Socket BindUdpSocket()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
socket.ReceiveTimeout = 20;
return socket;
}
private static void PumpRudpHandshake(
CultNetRudpSocketTransportConnection client,
CultNetRudpSocketTransportConnection server)
{
for (var attempt = 0; attempt < 20; attempt++)
{
server.ReceiveOnce();
client.ReceiveOnce();
server.ReceiveOnce();
if (client.Connected && server.Connected)
{
return;
}
Task.Delay(5).GetAwaiter().GetResult();
}
Assert.Fail("RUDP socket handshake did not complete.");
}
private static CultNetTransportFrame ReceiveRudpFrame(CultNetRudpSocketTransportConnection transport)
{
for (var attempt = 0; attempt < 20; attempt++)
{
var frame = transport.ReceiveOnce();
if (frame != null)
{
return frame;
}
Task.Delay(5).GetAwaiter().GetResult();
}
Assert.Fail("RUDP socket frame was not delivered.");
throw new InvalidOperationException("Unreachable.");
}
[Test]
public void EncryptDecrypt_Roundtrip()
{
@ -447,6 +494,52 @@ namespace GameCult.Networking.Tests
Is.EqualTo(new[] { "second", "third" }));
}
[Test]
public void RudpSocketTransport_HandshakesAndCarriesReliableOrderedSchemaFrames()
{
using var serverSocket = BindUdpSocket();
using var clientSocket = BindUdpSocket();
var serverEndPoint = serverSocket.LocalEndPoint!;
const uint connectionId = 0x10203040;
using var server = new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions
{
RuntimeId = "csharp-rudp-server",
Socket = serverSocket,
Mode = CultNetRudpSocketMode.Server,
ConnectionId = connectionId,
InitialSequence = 100,
ResendDelayMs = 25
});
using var client = new CultNetRudpSocketTransportConnection(new CultNetRudpSocketTransportOptions
{
RuntimeId = "csharp-rudp-client",
Socket = clientSocket,
Mode = CultNetRudpSocketMode.Client,
RemoteEndPoint = serverEndPoint,
ConnectionId = connectionId,
InitialSequence = 1,
ResendDelayMs = 25
});
client.Connect(Encoding.UTF8.GetBytes("join"));
PumpRudpHandshake(client, server);
Assert.That(client.Connected, Is.True);
Assert.That(server.Connected, Is.True);
client.Send("schema", Encoding.UTF8.GetBytes("client-state"));
var serverFrame = ReceiveRudpFrame(server);
Assert.That(serverFrame.ChannelId, Is.EqualTo("schema"));
Assert.That(Encoding.UTF8.GetString(serverFrame.Payload), Is.EqualTo("client-state"));
server.Send("schema", Encoding.UTF8.GetBytes("server-state"));
var clientFrame = ReceiveRudpFrame(client);
Assert.That(clientFrame.ChannelId, Is.EqualTo("schema"));
Assert.That(Encoding.UTF8.GetString(clientFrame.Payload), Is.EqualTo("server-state"));
Assert.That(server.Profile.Transports[0].Protocol, Is.EqualTo("rudp"));
Assert.That(client.Stats.FramesSent, Is.EqualTo(1));
Assert.That(server.Stats.FramesReceived, Is.EqualTo(1));
}
[Test]
public void CultNetSchemaMessageSerialization_RoundTrips_RawSnapshotResponse()
{