Home > OS >  How to trigger a websockets message from outside the routing() block in Ktor?
How to trigger a websockets message from outside the routing() block in Ktor?

Time:02-26

If I have an Kotlin application that wants to trigger outgoing Websocket messages in Ktor, I usually do this from within the relevant routing block. If I have a process outside of the routing block that wants to send a Websocket message, how can I trigger that?

CodePudding user response:

You need to store the session provided by the web socket connection and then you can send messages in that session:

var session: WebSocketSession? = null

try {
    client.ws {
        session = this
    }
} finally {
    // clear the session both when the socket is closed normally 
    // and when an error occurs, because it is no longer valid
    session = null
}
// other coroutine
session?.send(/*...*/)

CodePudding user response:

You can use coroutines' channels to send a Websocket session and receive it in a different place:

import io.ktor.application.*
import io.ktor.http.cio.websocket.*
import io.ktor.routing.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.websocket.*
import kotlinx.coroutines.channels.Channel

suspend fun main() {
    val sessions = Channel<WebSocketSession>()
    val server = embeddedServer(Netty, 5555, host = "0.0.0.0") {
        install(WebSockets) {}
        routing {
            webSocket("/socket") {
                sessions.send(this)
            }
        }
    }

    server.start()

    for (session in sessions) {
        session.outgoing.send(Frame.Text("From outside of the routing"))
    }
}
  • Related