import lyng.io.net

val host = "127.0.0.1"
val clientCount = 1000
val server = Net.tcpListen(0, host, clientCount, true) as TcpServer
val port = server.localAddress().port

fun payloadFor(index: Int) = "$index:${Random.nextInt()}:${Random.nextInt()}"

launch {
    try {
        while(true) {
            val client = server.accept() as TcpSocket
            launch {
                try {
                    val source = client.readLine()
                    if( source != null ) {
                        client.writeUtf8("pong: $source\n")
                        client.flush()
                    }
                } finally {
                    client.close()
                }
            }
        }
    } finally {
        server.close()
    }
}

val replies = (0..<clientCount).map { index ->
    val payload = payloadFor(index)
    launch {
        val socket = Net.tcpConnect(host, port) as TcpSocket
        try {
            socket.writeUtf8(payload + "\n")
            socket.flush()
            val reply = socket.readLine()
            assertEquals("pong: $payload", reply)
            reply
        } finally {
            socket.close()
        }
    }
}.joinAll()

assertEquals(clientCount, replies.size)
println("OK: $clientCount concurrent tcp clients")
