Hi all, is it possible to detect if a websocket se...
# ktor
v
Hi all, is it possible to detect if a websocket session was closed by the client? I'm getting some weird errors when a client closes the connection by leaving the page.
d
What kind of error do you have?
v
It's not related to ktor actually, it's due a channel that I create. In order to avoid having Websocket interfaces (such as Frame.Text) on my business classes I connected both using a channel
Copy code
webSocket("/arenas") {
                val channel = Channel<Status>()

                frameUpdater.subscribe(channel)
                for(status in channel){
                    outgoing.send(Frame.Text("timestamp: $status"))
                }
            }
it works fine when connections are alive, the
frameUpdater
has a suspended function that keeps producing data to the channel
d
And what happens when the use closes the tab?
v
but when the connection is closed, I get an error that the
channel
is no longer opened, and it's not like I'm getting the error on the producer side, it's actually at the
for
loop
d
that makes sense, probably it happens on the
outgoing.send
method
I guess that’s the expected behaviour, right?
v
same error at close
I guess if the error was in the send, that's what trigged my question. Error is on the receive side, which is odd. I should have better treatment for the producing side checking if the channel is closed and if it is remove it from the produce operation
d
I guess you should wrap the function after subscribe in a try..catch + finally, ignore expected errors for connection close, and unsubscribe on the finally block ?
the producer is not bound to that websocket as far as I understand from that snippet
as I understand you have a producer outside not bound to any websocket, and then you are doing a fanout to each websocket with the produced information
is that right?
v
that's correct
so it really seems that because the outgoing channel is closed the exception was being bubbled up, a bit weird where the stacktrace reports it though
Thanks for the help 🙂
👍 1
d
didn’t checked the stacktrace, though without asynchronous stacktraces enabled things are usually a bit weird, yes 🙂 so maybe it had sense somehow, but was far from obvious