Ktor-websocket library do nothing when trying to receive data on client

1.1k Views Asked by At

I am currently trying to connect our Kotlin Multiplatform Project to websockets. I would like to use ktor-websockets library to receive some updates from our backend but onfortunately when I run this code, nothing happens:

client.webSocket(
            port = 80,
            method = HttpMethod.Get,
            host = "https://uat-betws.sts.pl",
            path = "/ticket?token=eyJzdWIiOiI0ZmY5Y2E1Mi02ZmEwLTRiYWYtODlhYS0wODM1NGE2MTU0YjYiLCJpYXQiOjE2MTk4MDAwNzgsImV4cCI6MTYxOTgwMzY3OH0.oIaXH-nFDpMklp4FSJWMtsM7ECSIfuNF99tTQxiEALM"
        )
        {
            for (message in incoming) {
                message as? Frame.Text ?: continue
                val receivedText = message.readText()
                println(receivedText)
            }
            // Consume all incoming websockets on this url
            this.incoming.consumeAsFlow().collect {
                logger.d("Received ticket status websocket of type ${it.frameType.name}")
                if (it is Frame.Text) {
                    Json.decodeFromString<TicketStatusResponse>(it.readText())
                }
            }
        }

Does somebody have any experience with ktor-websockets library? There is almost no documentation so maybe I am doing something wrong. Thank you

1

There are 1 best solutions below

0
On

As the documentation says

Ktor provides Websocket client support for the following engines: CIO, OkHttp, Js.

This means that it works only on JVM/JS, you're probably targeting iOS. It's not yet supported, you can follow issue KTOR-363 for updates

For sure the team is working on it, but for now you had to implement it by yourself using expect/actual, you can check out official example

An other possible problem in your code: host shouldn't include https://, if you're using ssl, you should add an other parameter:

request = {
    url.protocol = URLProtocol.WSS
}

Or use client.wss(...) - which is just a short form for the same operation