lyng/examples/tcpserver.lyng

58 lines
1.3 KiB
Plaintext

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): String {
"$index:${Random.nextInt()}:${Random.nextInt()}"
}
fun handleClient(client: TcpSocket) {
try {
val source = client.readLine()
if( source != null ) {
client.writeUtf8("pong: $source\n")
client.flush()
}
} finally {
client.close()
}
}
launch {
try {
for( i in 0..<clientCount ) {
val client = server.accept() as TcpSocket
launch {
handleClient(client)
}
}
} 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)
val summary = "OK: $clientCount concurrent tcp clients"
println(summary)
summary