Created
January 13, 2021 18:20
-
-
Save Tyluur/167c0bf21d172d7d207c4e0240502e72 to your computer and use it in GitHub Desktop.
Listen on a port using ktor (co-routine support) [TCP]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun listen() { | |
runBlocking { | |
val exec = Executors.newCachedThreadPool() | |
val selector = ActorSelectorManager(exec.asCoroutineDispatcher()) | |
val socketBuilder = aSocket(selector) | |
val server = | |
socketBuilder.tcp().bind(InetSocketAddress("localhost", NetworkConstants.PORT)) | |
launch { | |
val socket = server.accept() | |
logger.info { "Socket accepted: ${socket.remoteAddress}" } | |
val input = socket.openReadChannel() | |
val output = socket.openWriteChannel() | |
while (true) { | |
try { | |
val length = input.availableForRead | |
} catch (e: Throwable) { | |
e.printStackTrace() | |
socket.close() | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment