diff --git a/docs/cultnet-transport-parity.md b/docs/cultnet-transport-parity.md index 0ebe3cab..a4e4188e 100644 --- a/docs/cultnet-transport-parity.md +++ b/docs/cultnet-transport-parity.md @@ -29,7 +29,7 @@ CultNet owns cross-runtime transport semantics: | 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 | | Python `cultcache-py` | TCP sockets with 4-byte length-prefixed MessagePack frames for local CultMesh/CultNet server and client; single-peer RUDP socket transport exists in the library | Endpoint lists and CultMesh peer/Verse catalogs | UDP socket binding for the shared RUDP reliability owner | -| Kotlin `cultmesh-kotlin` | Minimal WebSocket-like lane over TCP socket | None found in the live package | Thin client surface | +| Kotlin `cultmesh-kotlin` | Minimal WebSocket-like lane over TCP socket; single-peer RUDP socket transport exists in the library | None found in the live package | UDP socket binding for the shared RUDP reliability owner, with build-script self-test | The live split is therefore: payload language is converging, transport language is not. @@ -165,15 +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. -- C#, TypeScript, Rust, and Python now have socket-backed RUDP transport +- C#, TypeScript, Rust, Python, and Kotlin 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; C#, - Rust, and Python expose the same transport frame/stats shape through + Rust, Python, and Kotlin 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. +- The remaining parity work is to deepen Python's server-side use of its port + and move each runtime's existing TCP/LiteNetLib/WebSocket bodies behind those + ports. ## RUDP Packet Contract V0 diff --git a/packages/cultmesh-kotlin/README.md b/packages/cultmesh-kotlin/README.md index e00c1ef9..d2662b49 100644 --- a/packages/cultmesh-kotlin/README.md +++ b/packages/cultmesh-kotlin/README.md @@ -3,7 +3,8 @@ Kotlin/JVM and Android client substrate for CultCache, CultNet, and CultMesh. It provides typed MessagePack document codecs, a tiny WebSocket CultNet lane, -an in-memory CultCache, and the first Eve dashboard/sensor document contracts. +a single-peer CultNet RUDP socket transport, an in-memory CultCache, and the +first Eve dashboard/sensor document contracts. `EveDashboardStateDocument` mirrors the CultUI-shaped dashboard surface contract: `surface.root` is the retained UI tree, `surface.assets` carries cacheable media @@ -22,3 +23,5 @@ powershell -ExecutionPolicy Bypass -File .\packages\cultmesh-kotlin\build.ps1 ``` The build writes `artifacts/cultmesh-kotlin/cultmesh-kotlin.jar`. +It also runs the built-in RUDP packet fixture and localhost UDP socket +self-test. diff --git a/packages/cultmesh-kotlin/build.ps1 b/packages/cultmesh-kotlin/build.ps1 index a5d46e05..7802d8eb 100644 --- a/packages/cultmesh-kotlin/build.ps1 +++ b/packages/cultmesh-kotlin/build.ps1 @@ -24,4 +24,6 @@ New-Item -ItemType Directory -Force $out | Out-Null $sources = Get-ChildItem $src -Recurse -Filter *.kt | Select-Object -ExpandProperty FullName & $kotlinc @sources -jvm-target 1.8 -classpath $kotlinStdlib -d $jarPath if ($LASTEXITCODE -ne 0) { throw "kotlinc failed with exit code $LASTEXITCODE" } +& $java -cp "$jarPath;$kotlinStdlib" org.gamecult.cultmesh.CultMeshKt +if ($LASTEXITCODE -ne 0) { throw "cultmesh-kotlin self-test failed with exit code $LASTEXITCODE" } Write-Host "Built $jarPath" diff --git a/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt b/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt index e8132601..b9aec731 100644 --- a/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt +++ b/packages/cultmesh-kotlin/src/main/kotlin/org/gamecult/cultmesh/CultMesh.kt @@ -7,12 +7,20 @@ import java.io.EOFException import java.io.IOException import java.io.InputStream import java.io.OutputStream +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.InetAddress +import java.net.InetSocketAddress import java.net.Socket +import java.net.SocketTimeoutException import java.net.URI import java.nio.ByteBuffer import java.nio.charset.StandardCharsets import java.security.SecureRandom +import java.time.Instant +import java.util.ArrayDeque import java.util.Base64 +import java.util.TreeMap interface CultDocumentCodec { val documentType: String @@ -56,6 +64,539 @@ class CultMeshNode( data class CultNetFrame(val opcode: Int, val payload: ByteArray) +data class CultNetTransportStats( + val bytesReceived: Long = 0, + val bytesSent: Long = 0, + val framesReceived: Long = 0, + val framesSent: Long = 0, +) + +data class CultNetTransportFrame(val channelId: String, val payload: ByteArray) + +data class CultNetTransportProfile( + val schemaVersion: String = "cultnet.transport_profile.v0", + val runtimeId: String, + val transports: List, +) + +data class CultNetTransportDescriptor( + val transportId: String, + val protocol: String, + val host: String? = null, + val port: Int? = null, + val wireContracts: List = listOf("cultnet.schema.v0"), + val channels: List, +) + +data class CultNetTransportChannel( + val channelId: String, + val delivery: String, + val ordering: String, + val maxPayloadBytes: Int? = null, + val maxFragmentBytes: Int? = null, +) + +fun createRudpTransportProfile( + runtimeId: String, + transportId: String = "rudp", + host: String? = null, + port: Int? = null, + maxPayloadBytes: Int? = null, + maxFragmentBytes: Int? = null, +): CultNetTransportProfile = CultNetTransportProfile( + runtimeId = runtimeId, + transports = listOf( + CultNetTransportDescriptor( + transportId = transportId.ifBlank { "rudp" }, + protocol = "rudp", + host = host, + port = port, + channels = listOf( + CultNetTransportChannel("schema", "reliable", "ordered", maxPayloadBytes, maxFragmentBytes), + CultNetTransportChannel("latest", "unreliable", "sequenced", maxPayloadBytes, maxFragmentBytes), + CultNetTransportChannel("realtime", "unreliable", "unordered", maxPayloadBytes, maxFragmentBytes), + ), + ), + ), +) + +enum class CultNetRudpPacketType(val code: Int) { + Connect(1), + Accept(2), + Data(3), + Ack(4), + Ping(5), + Pong(6), + Disconnect(7); + + companion object { + fun fromCode(code: Int): CultNetRudpPacketType = + values().firstOrNull { it.code == code } ?: throw IOException("Unsupported CultNet RUDP packet type $code") + } +} + +data class CultNetRudpPacket( + val packetType: CultNetRudpPacketType, + val connectionId: Long, + val sequence: Long, + val ack: Long, + val ackMask: Long, + val channelId: String, + val reliable: Boolean = false, + val ordered: Boolean = false, + val sequenced: Boolean = false, + val fragmentId: Int = 0, + val fragmentIndex: Int = 0, + val fragmentCount: Int = 0, + val payload: ByteArray = ByteArray(0), +) + +data class CultNetRudpDeliveredFrame(val channelId: String, val payload: ByteArray, val sequence: Long) +data class CultNetRudpReceiveResult( + val delivered: List = emptyList(), + val reply: CultNetRudpPacket? = null, +) + +data class CultNetRudpSessionOptions( + val connectionId: Long, + val initialSequence: Long = 1, + val resendDelayMs: Long = 250, +) + +data class CultNetRudpSendOptions( + val reliable: Boolean = false, + val ordered: Boolean = false, + val sequenced: Boolean = false, + val nowMs: Long = 0, +) + +private data class PendingReliablePacket(var packet: CultNetRudpPacket, var lastSentAtMs: Long) + +class CultNetRudpSession(options: CultNetRudpSessionOptions) { + val connectionId: Long = uint32(options.connectionId, "connectionId") + val resendDelayMs: Long = options.resendDelayMs + private var nextSequence = uint32(options.initialSequence, "initialSequence") + var connected: Boolean = false + private set + private var highestReceivedSequence: Long? = null + private val receivedSequences = linkedSetOf() + private val pendingReliable = linkedMapOf() + private val orderedNextSequenceByChannel = linkedMapOf() + private val orderedBuffers = linkedMapOf>() + + val pendingReliableSequences: List + get() = pendingReliable.keys.sorted() + + fun createConnect(nowMs: Long = 0, payload: ByteArray = ByteArray(0)): CultNetRudpPacket { + val packet = createPacket(CultNetRudpPacketType.Connect, "control", payload, reliable = true, ordered = true) + trackReliable(packet, nowMs) + return packet + } + + fun acceptConnect(packet: CultNetRudpPacket, nowMs: Long = 0, payload: ByteArray = ByteArray(0)): CultNetRudpPacket { + requireConnection(packet) + if (packet.packetType != CultNetRudpPacketType.Connect) throw IOException("Expected RUDP connect packet, got ${packet.packetType}") + rememberReceived(packet.sequence) + connected = true + val response = createPacket(CultNetRudpPacketType.Accept, "control", payload, reliable = true, ordered = true) + trackReliable(response, nowMs) + return response + } + + fun send(channelId: String, payload: ByteArray, options: CultNetRudpSendOptions = CultNetRudpSendOptions()): CultNetRudpPacket { + if (!connected) throw IOException("Cannot send RUDP data before the session is connected") + val packet = createPacket(channelId = channelId, packetType = CultNetRudpPacketType.Data, payload = payload, reliable = options.reliable, ordered = options.ordered, sequenced = options.sequenced) + if (packet.reliable) trackReliable(packet, options.nowMs) + return packet + } + + fun receive(packet: CultNetRudpPacket, nowMs: Long = 0): CultNetRudpReceiveResult { + @Suppress("UNUSED_VARIABLE") + val ignoredNow = nowMs + requireConnection(packet) + applyAcknowledgements(packet) + when (packet.packetType) { + CultNetRudpPacketType.Accept -> { + rememberReceived(packet.sequence) + connected = true + return CultNetRudpReceiveResult() + } + CultNetRudpPacketType.Ping -> { + rememberReceived(packet.sequence) + return CultNetRudpReceiveResult(reply = createPacket(CultNetRudpPacketType.Pong, "control", packet.payload)) + } + CultNetRudpPacketType.Ack, CultNetRudpPacketType.Pong -> { + rememberReceived(packet.sequence) + return CultNetRudpReceiveResult() + } + CultNetRudpPacketType.Data -> Unit + else -> return CultNetRudpReceiveResult() + } + + val duplicate = receivedSequences.contains(packet.sequence) + rememberReceived(packet.sequence) + if (duplicate) return CultNetRudpReceiveResult() + val frame = CultNetRudpDeliveredFrame(packet.channelId, packet.payload.copyOf(), packet.sequence) + return CultNetRudpReceiveResult(delivered = if (packet.ordered) deliverOrdered(frame) else listOf(frame)) + } + + fun createAck(): CultNetRudpPacket = createPacket(CultNetRudpPacketType.Ack, "control", ByteArray(0)) + + fun dueResends(nowMs: Long): List = + pendingReliable.values + .filter { nowMs - it.lastSentAtMs >= resendDelayMs } + .onEach { it.lastSentAtMs = nowMs } + .map { it.packet.copy(payload = it.packet.payload.copyOf()) } + .sortedBy { it.sequence } + + private fun createPacket( + packetType: CultNetRudpPacketType, + channelId: String, + payload: ByteArray, + reliable: Boolean = false, + ordered: Boolean = false, + sequenced: Boolean = false, + ): CultNetRudpPacket { + val sequence = nextSequence + nextSequence = uint32(nextSequence + 1, "sequence") + val (ack, ackMask) = ackState() + return CultNetRudpPacket(packetType, connectionId, sequence, ack, ackMask, channelId, reliable, ordered, sequenced, payload = payload.copyOf()) + } + + private fun trackReliable(packet: CultNetRudpPacket, nowMs: Long) { + pendingReliable[packet.sequence] = PendingReliablePacket(packet.copy(payload = packet.payload.copyOf()), nowMs) + } + + private fun applyAcknowledgements(packet: CultNetRudpPacket) { + pendingReliable.remove(packet.ack) + for (bit in 0 until 32) { + if ((packet.ackMask and (1L shl bit)) != 0L && packet.ack > bit) { + pendingReliable.remove(packet.ack - bit - 1) + } + } + } + + private fun rememberReceived(sequence: Long) { + receivedSequences.add(sequence) + if (highestReceivedSequence == null || sequence > highestReceivedSequence!!) highestReceivedSequence = sequence + } + + private fun ackState(): Pair { + val ack = highestReceivedSequence ?: 0 + var ackMask = 0L + for (bit in 0 until 32) { + if (ack > bit && receivedSequences.contains(ack - bit - 1)) ackMask = ackMask or (1L shl bit) + } + return ack to ackMask + } + + private fun deliverOrdered(frame: CultNetRudpDeliveredFrame): List { + val next = orderedNextSequenceByChannel[frame.channelId] + if (next == null) { + orderedNextSequenceByChannel[frame.channelId] = frame.sequence + 1 + return listOf(frame) + drainOrdered(frame.channelId) + } + if (frame.sequence < next) return emptyList() + if (frame.sequence > next) { + orderedBuffers.getOrPut(frame.channelId) { TreeMap() }[frame.sequence] = frame + return emptyList() + } + orderedNextSequenceByChannel[frame.channelId] = next + 1 + return listOf(frame) + drainOrdered(frame.channelId) + } + + private fun drainOrdered(channelId: String): List { + val delivered = mutableListOf() + val buffer = orderedBuffers[channelId] ?: return delivered + while (true) { + val next = orderedNextSequenceByChannel[channelId] ?: break + val frame = buffer.remove(next) ?: break + delivered.add(frame) + orderedNextSequenceByChannel[channelId] = next + 1 + } + return delivered + } + + private fun requireConnection(packet: CultNetRudpPacket) { + if (packet.connectionId != connectionId) throw IOException("RUDP packet connection id ${packet.connectionId} does not match $connectionId") + } +} + +enum class CultNetRudpSocketMode { Client, Server } + +class CultNetRudpSocketTransportConnection( + private val socket: DatagramSocket, + private val mode: CultNetRudpSocketMode, + runtimeId: String, + connectionId: Long, + remoteAddress: InetSocketAddress? = null, + initialSequence: Long = 1, + resendDelayMs: Long = 250, +) : AutoCloseable { + private val session = CultNetRudpSession(CultNetRudpSessionOptions(connectionId, initialSequence, resendDelayMs)) + private var remote = remoteAddress + private val delivered = ArrayDeque() + private var bytesReceived = 0L + private var bytesSent = 0L + private var framesReceived = 0L + private var framesSent = 0L + + val profile: CultNetTransportProfile = createRudpTransportProfile( + runtimeId = runtimeId, + host = socket.localAddress.hostAddress, + port = socket.localPort, + ) + val connected: Boolean get() = session.connected + val stats: CultNetTransportStats get() = CultNetTransportStats(bytesReceived, bytesSent, framesReceived, framesSent) + + fun connect(payload: ByteArray = ByteArray(0)) { + if (mode != CultNetRudpSocketMode.Client) throw IOException("Only a client RUDP socket transport can initiate connect") + sendPacket(session.createConnect(nowMs(), payload)) + } + + fun send(channelId: String, payload: ByteArray) { + sendPacket(session.send(channelId, payload, channelSendOptions(channelId, nowMs()))) + framesSent += 1 + } + + fun receiveOnce(): CultNetTransportFrame? { + if (!delivered.isEmpty()) return delivered.removeFirst() + val buffer = ByteArray(65535) + val datagram = DatagramPacket(buffer, buffer.size) + try { + socket.receive(datagram) + } catch (_: SocketTimeoutException) { + return null + } + bytesReceived += datagram.length.toLong() + val remoteNow = InetSocketAddress(datagram.address, datagram.port) + if (remote == null) { + remote = remoteNow + } else if (remote != remoteNow) { + return null + } + val packet = decodeRudpPacket(buffer.copyOf(datagram.length)) + if (mode == CultNetRudpSocketMode.Server && packet.packetType == CultNetRudpPacketType.Connect) { + sendPacket(session.acceptConnect(packet, nowMs())) + return null + } + val result = session.receive(packet, nowMs()) + result.reply?.let { sendPacket(it) } + result.delivered.forEach { + delivered.add(CultNetTransportFrame(it.channelId, it.payload)) + framesReceived += 1 + } + val frame = if (delivered.isEmpty()) null else delivered.removeFirst() + if (packet.packetType == CultNetRudpPacketType.Accept || frame != null) sendPacket(session.createAck()) + return frame + } + + fun pollResends() { + session.dueResends(nowMs()).forEach { sendPacket(it) } + } + + private fun sendPacket(packet: CultNetRudpPacket) { + val target = remote ?: throw IOException("RUDP socket transport does not have a remote endpoint") + val wire = encodeRudpPacket(packet) + socket.send(DatagramPacket(wire, wire.size, target.address, target.port)) + bytesSent += wire.size.toLong() + } + + override fun close() { + socket.close() + } +} + +private val rudpMagic = byteArrayOf(0x43, 0x4e, 0x52, 0x30) +private const val rudpVersion = 0 +private const val rudpFixedHeaderBytes = 36 + +fun encodeRudpPacket(packet: CultNetRudpPacket): ByteArray { + val channelId = packet.channelId.toByteArray(StandardCharsets.UTF_8) + if (channelId.size > 255) throw IOException("CultNet RUDP channel id cannot exceed 255 UTF-8 bytes") + val headerBytes = rudpFixedHeaderBytes + channelId.size + val payload = packet.payload + val wire = ByteArray(headerBytes + payload.size) + val view = ByteBuffer.wrap(wire) + view.put(rudpMagic) + view.put(rudpVersion.toByte()) + view.put(packet.packetType.code.toByte()) + view.put(encodeRudpFlags(packet).toByte()) + view.put(headerBytes.toByte()) + view.putInt(uint32(packet.connectionId, "connectionId").toInt()) + view.putInt(uint32(packet.sequence, "sequence").toInt()) + view.putInt(uint32(packet.ack, "ack").toInt()) + view.putInt(uint32(packet.ackMask, "ackMask").toInt()) + view.putShort(uint16(packet.fragmentId, "fragmentId").toShort()) + view.putShort(uint16(packet.fragmentIndex, "fragmentIndex").toShort()) + view.putShort(uint16(packet.fragmentCount, "fragmentCount").toShort()) + view.putInt(payload.size) + view.put(channelId.size.toByte()) + view.put(0) + view.put(channelId) + view.put(payload) + return wire +} + +fun decodeRudpPacket(wire: ByteArray): CultNetRudpPacket { + if (wire.size < rudpFixedHeaderBytes) throw IOException("CultNet RUDP packet is shorter than the fixed header") + if (!wire.copyOfRange(0, 4).contentEquals(rudpMagic)) throw IOException("CultNet RUDP packet has the wrong magic") + val view = ByteBuffer.wrap(wire) + if ((wire[4].toInt() and 0xff) != rudpVersion) throw IOException("Unsupported CultNet RUDP packet version ${wire[4].toInt() and 0xff}") + val type = CultNetRudpPacketType.fromCode(wire[5].toInt() and 0xff) + val flags = wire[6].toInt() and 0xff + val headerBytes = wire[7].toInt() and 0xff + val channelIdLength = wire[34].toInt() and 0xff + if (headerBytes != rudpFixedHeaderBytes + channelIdLength) throw IOException("CultNet RUDP packet header length does not match the channel id length") + val payloadLength = view.getInt(30) + if (wire.size != headerBytes + payloadLength) throw IOException("CultNet RUDP packet payload length does not match the packet size") + return CultNetRudpPacket( + packetType = type, + connectionId = view.getInt(8).toLong() and 0xffffffffL, + sequence = view.getInt(12).toLong() and 0xffffffffL, + ack = view.getInt(16).toLong() and 0xffffffffL, + ackMask = view.getInt(20).toLong() and 0xffffffffL, + fragmentId = view.getShort(24).toInt() and 0xffff, + fragmentIndex = view.getShort(26).toInt() and 0xffff, + fragmentCount = view.getShort(28).toInt() and 0xffff, + channelId = String(wire, rudpFixedHeaderBytes, channelIdLength, StandardCharsets.UTF_8), + reliable = (flags and 0b0000_0001) != 0, + ordered = (flags and 0b0000_0010) != 0, + sequenced = (flags and 0b0000_0100) != 0, + payload = wire.copyOfRange(headerBytes, wire.size), + ) +} + +private fun encodeRudpFlags(packet: CultNetRudpPacket): Int = + (if (packet.reliable) 0b0000_0001 else 0) or + (if (packet.ordered) 0b0000_0010 else 0) or + (if (packet.sequenced) 0b0000_0100 else 0) or + (if (packet.fragmentCount > 0) 0b0000_1000 else 0) + +private fun channelSendOptions(channelId: String, nowMs: Long): CultNetRudpSendOptions = when (channelId) { + "schema" -> CultNetRudpSendOptions(reliable = true, ordered = true, nowMs = nowMs) + "latest" -> CultNetRudpSendOptions(sequenced = true, nowMs = nowMs) + else -> CultNetRudpSendOptions(nowMs = nowMs) +} + +private fun uint32(value: Long, fieldName: String): Long { + if (value < 0 || value > 0xffffffffL) throw IOException("CultNet RUDP $fieldName must fit in uint32") + return value +} + +private fun uint16(value: Int, fieldName: String): Int { + if (value < 0 || value > 0xffff) throw IOException("CultNet RUDP $fieldName must fit in uint16") + return value +} + +private fun nowMs(): Long = Instant.now().toEpochMilli() + +fun main() { + rudpPacketCodecUsesDeterministicReliableOrderedFixture() + rudpSocketTransportHandshakesAndCarriesReliableOrderedSchemaFrames() +} + +private fun rudpPacketCodecUsesDeterministicReliableOrderedFixture() { + val encoded = encodeRudpPacket( + CultNetRudpPacket( + packetType = CultNetRudpPacketType.Data, + connectionId = 0x01020304, + sequence = 0x0000002a, + ack = 0x00000029, + ackMask = 0x80000001, + channelId = "schema", + reliable = true, + ordered = true, + fragmentId = 7, + fragmentIndex = 1, + fragmentCount = 3, + payload = "hello".toByteArray(StandardCharsets.UTF_8), + ), + ) + + check(encoded.joinToString("") { "%02x".format(it.toInt() and 0xff) } == "434e523000030b2a010203040000002a0000002980000001000700010003000000050600736368656d6168656c6c6f") + val decoded = decodeRudpPacket(encoded) + check(decoded.packetType == CultNetRudpPacketType.Data) + check(decoded.connectionId == 0x01020304L) + check(decoded.sequence == 0x0000002aL) + check(decoded.ack == 0x00000029L) + check(decoded.ackMask == 0x80000001L) + check(decoded.channelId == "schema") + check(decoded.reliable) + check(decoded.ordered) + check(!decoded.sequenced) + check(decoded.fragmentId == 7) + check(decoded.fragmentIndex == 1) + check(decoded.fragmentCount == 3) + check(String(decoded.payload, StandardCharsets.UTF_8) == "hello") +} + +private fun rudpSocketTransportHandshakesAndCarriesReliableOrderedSchemaFrames() { + val loopback = InetAddress.getByName("127.0.0.1") + val serverSocket = DatagramSocket(0, loopback).also { it.soTimeout = 20 } + val clientSocket = DatagramSocket(0, loopback).also { it.soTimeout = 20 } + val connectionId = 0x10203040L + CultNetRudpSocketTransportConnection( + socket = serverSocket, + mode = CultNetRudpSocketMode.Server, + runtimeId = "kotlin-rudp-server", + connectionId = connectionId, + initialSequence = 100, + resendDelayMs = 25, + ).use { server -> + CultNetRudpSocketTransportConnection( + socket = clientSocket, + mode = CultNetRudpSocketMode.Client, + runtimeId = "kotlin-rudp-client", + connectionId = connectionId, + remoteAddress = InetSocketAddress(loopback, serverSocket.localPort), + initialSequence = 1, + resendDelayMs = 25, + ).use { client -> + client.connect("join".toByteArray(StandardCharsets.UTF_8)) + pumpRudpHandshake(client, server) + check(client.connected) + check(server.connected) + + client.send("schema", "client-state".toByteArray(StandardCharsets.UTF_8)) + val serverFrame = receiveRudpFrame(server) + check(serverFrame.channelId == "schema") + check(String(serverFrame.payload, StandardCharsets.UTF_8) == "client-state") + + server.send("schema", "server-state".toByteArray(StandardCharsets.UTF_8)) + val clientFrame = receiveRudpFrame(client) + check(clientFrame.channelId == "schema") + check(String(clientFrame.payload, StandardCharsets.UTF_8) == "server-state") + check(server.profile.transports.first().protocol == "rudp") + check(client.stats.framesSent == 1L) + check(server.stats.framesReceived == 1L) + } + } +} + +private fun pumpRudpHandshake( + client: CultNetRudpSocketTransportConnection, + server: CultNetRudpSocketTransportConnection, +) { + repeat(20) { + server.receiveOnce() + client.receiveOnce() + server.receiveOnce() + if (client.connected && server.connected) return + Thread.sleep(5) + } + error("RUDP socket handshake did not complete") +} + +private fun receiveRudpFrame(transport: CultNetRudpSocketTransportConnection): CultNetTransportFrame { + repeat(20) { + val frame = transport.receiveOnce() + if (frame != null) return frame + Thread.sleep(5) + } + error("RUDP socket frame was not delivered") +} + class CultNetWebSocketClient private constructor( private val socket: Socket, private val input: InputStream,