https://kotlinlang.org logo
#ktor
Title
# ktor
a

Andi J

06/09/2022, 7:03 PM
Hi, I'm working with WebSockets at the moment and can't manage to detect closing frames. This is what the documentation says:
When handling a session, you can check a frame type, for example:
• Frame.Text is a text frame. For this frame type, you can read its content using Frame.Text.readText().
• Frame.Binary is a binary frame. For this type, you can read its content using Frame.Binary.readBytes().
• Frame.Close is a closing frame. You can call Frame.Close.readReason() to get a close reason for the current session.
Use the close function to send a close frame with the specified reason.
I need to remove my Connection instance from a set, when the channel is closed. But in this code the cleanup is never called, when the other side uses the close function:
Copy code
try {
    for (frame in session.incoming) {
        when (frame) {
            is Frame.Text -> {
                // ...
            }
            is Frame.Close -> {
                // Do cleanup
            }
            else -> {}
        }
    }
} catch (e: ClosedReceiveChannelException) {
    println("onClose ${session.closeReason.await()}")
    // Do cleanup
} catch (e: Throwable) {
    println("onError ${session.closeReason.await()}")
    // Do cleanup
}
So how do I react to closing frames correctly?
a

Aleksei Tirman [JB]

06/09/2022, 7:44 PM
In a simple server sample a
catch
block with the
ClosedReceiveChannelException
or a
finally
block is called when a connection is closed. Do you develop an application with a server or a client?
a

Andi J

06/09/2022, 8:33 PM
Thanks! The
catch
block isn't called, but the
finally
block is indeed entered on the server. 🙂 I was so confused, that neither the
when
branch for
Frame.Close
nor the
catch
did anything, so I didn't think about
finally
. I think the documentation is misleading. It states, that you can check the frame type, but closing frames don't appear when iterating over
incoming
.
a

Aleksei Tirman [JB]

06/09/2022, 9:45 PM
Yes, that’s intended. If you want the full control over websockets negotiation then you can use raw Websockets https://api.ktor.io/ktor-server/ktor-server-plugins/ktor-server-websockets/io.ktor.server.websocket/web-socket-raw.html