Ktor: How to subscribe events onClose, onConnect, onError in websocket ?

Created on 18 Oct 2018  路  5Comments  路  Source: ktorio/ktor

I can only subscribe to the message event

            webSocket("api") {
                incoming.consumeEach { frame ->
                    when (frame) {
                        is Frame.Close -> println("close") // not work
                        is Frame.Binary -> {
                            val length = frame.buffer.remaining()
                            val byteArray = ByteArray(length)
                            frame.buffer.get(byteArray)
                            val request = Mapper.mapTo<Request<Any>>(byteArray)
                        }
                    }
                }
            }

Such an opportunity will be in the future?

question

Most helpful comment

@soywiz Since this approach looks different too the classic approach we probably can add a small notice at our page http://ktor.io/servers/features/websockets.html

All 5 comments

  • onConnect: makes no sense as user's block is only invoked when connected
  • onClose: incoming channel simply gets closed, a close reason could be obtained from closeReason deferred
  • onError: incoming channel gets closed with error (attempt to receive on this channel will cause it to throw an exception) and/or closeReason could be completed with the reason

@cy6erGn0m Thanks for the answer, there are few examples and information on the websocket in the documentation

@soywiz Since this approach looks different too the classic approach we probably can add a small notice at our page http://ktor.io/servers/features/websockets.html

@soywiz Since this approach looks different too the classic approach we probably can add a small notice at our page http://ktor.io/servers/features/websockets.html

This link is dead now. But the content is available here: https://ktor.io/docs/websocket.html#standard-events

Oh thank you.

Was this page helpful?
0 / 5 - 0 ratings