How to use the coroutines-based Ktor websocket client with Android?

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. :smiley:)

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).

you must use a websocket sessions. also i can see infinity loop in UI thread, thats not good…
check this code example:

ChatRepository: ChatRepository.kt · GitHub
ChatRepositiryImpl: ChatRepositoryImpl.kt · GitHub
MainActivity: MainActivity.kt · GitHub

hope it will helps you :slight_smile: