01/15/2021, 10:42 AM
Hey guys, can someone explain to me how the proper closing of sockets in ktor should look like? I have something like:
override suspend fun <T> openConnection(socketAddress: InetSocketAddress, block: suspend (Socket) -> T): T {
    val socketJob = Job()
    var selectorManager: SelectorManager? = null
    var socket: Socket? = null
    try {
        selectorManager = ActorSelectorManager(socketJob + coroutineContext)
        socket = aSocket(selectorManager)
            .connect(socketAddress) {
                socketTimeout = 10_000
        return block(socket)
    } finally {
        withContext(NonCancellable) {
The channels opened in block() are closed in all cases. What I’m observing (attached the screenshots) is that shutdownOutput() is sent, so the client socket gets into the FIN_WAIT_1, but there is no way for me AFAIK to wait for the whole 4-way TCP close to properly finish, so I end up with server socket that is still open and doesn’t know the client is dead. Sometimes the server sockets ends up in the CLOSE_WAIT as well. I’ve checked the timeout tests in and if you place a breakpoint after
, I’m seeing the same socket behaviour. Is it something that I’m missing or there is a problem in ktor? 🙂 thanks