如何从 Ktor 中的routing()块外部触发websockets消息?

发布于 2025-01-09 19:41:01 字数 110 浏览 1 评论 0原文

如果我有一个 Kotlin 应用程序想要在 Ktor 中触发传出 Websocket 消息,我通常会在相关路由块中执行此操作。如果我在路由块外部有一个进程想要发送 Websocket 消息,我该如何触发它?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

老子叫无熙 2025-01-16 19:41:01

您需要存储 Web 套接字连接提供的会话,然后您可以在该会话中发送消息:

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(/*...*/)

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(/*...*/)
Oo萌小芽oO 2025-01-16 19:41:01

您可以使用 协程通道 发送 Websocket会话并在不同的地方接收它:

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"))
    }
}

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"))
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文