I’m fairly new to Kotlin. I hope this is on topic here. I’d like to use a Ktor websocket client in an Android app.
I can create a Websocket connection like this:
findViewById<Button>(R.id.buttonTest).setOnClickListener {
val client = HttpClient(OkHttp) {
install(WebSockets) {}
}
runBlocking {
client.webSocket(method = HttpMethod.Get, host = "127.0.0.1", port = 1234, path = "/websocket") {
while(true) {
val othersMessage = incoming.receive() as? Frame.Text
Log.d("WS", othersMessage?.readText() ?: "<null>")
}
}
}
}
It will connect to the websocket and print the first message it receives. (After that it crashes because the connection and thus the channel gets closed, but that’s not the point here. )
Now the part where I don’t know how to plug things together:
The websocket is only available in that lambda that gets passed to .webSocket
.
But in my Android app I need to open the websocket connection when the activity resumes (possibly handling reconnect, but I’ll worry about that later) keep it open while the activity is active and then be able to call send()
for example in an onClick handler of a button. When a message comes in at any point I need to be able to handle it, for example by logging it (for now).