Hey! How do you send data to a websocket outside o...
# ktor
h
Hey! How do you send data to a websocket outside of the client.wss block e.g
Copy code
class example {
    private val ktorClient = HttpClient(Js) {
        install(WebSockets)
    }
    override suspend fun open() {
        ktorClient.wss(
            method = HttpMethod.Get,
            host = "localhost",
            port = 80, path = "/example"
        ) {
            
            val frame = incoming.receive()
            when (frame) {
                is Frame.Text -> println(frame.readText())
                is Frame.Binary -> println(frame.readBytes())
            }
        }
    }

    override fun close() {
        TODO("Not yet implemented")
    }

    override fun <T> sendData(data: T) {
        // Send to WS here
    }
}
r
Check out the websocket tutorial. You can launch a coroutine for both incoming and outgoing messages, so they can both run. In your case, a Channel or Flow that your client code submits the send requests to and your open connection consumes seems like it's probably the way to go. https://ktor.io/docs/creating-web-socket-chat.html
h
@rharter I read that but dont know how i would do it in my example code that I incuded
r
Make a channel as a property of the example class, and duplicate this, except replace incoming with the channel, and send the message as a result. Then the rest is copy/paste.
Copy code
suspend fun DefaultClientWebSocketSession.outputMessages() {
    try {
        for (message in incoming) {
            message as? Frame.Text ?: continue
            println(message.readText())
        }
    } catch (e: Exception) {
        println("Error while receiving: " + e.localizedMessage)
    }
}
h
like this @rharter?
Copy code
private val messageChannel: Channel<String> = Channel<String>()

    suspend fun DefaultClientWebSocketSession.messageChannel() {
        try {
            for (message in messageChannel) {
                message as? Frame.Text ?: continue
                send(message)
                println("Sending Message: ${message.readText()}")
            }
        } catch (e: Exception) {
            println("Error while receiving: " + e.message)
        }
    }
r
That's the right idea. Looks like you'll need to fix up the types of the message channel, but that's the idea.