【问题标题】:Current web socket session in ktorktor 中的当前 Web 套接字会话
【发布时间】:2024-01-19 04:55:01
【问题描述】:

如何获取当前的网络套接字会话? 我有一个想法做这样的事情:

webSocket("/echo") {
            println("WebSocket connection")

            val thisConnection = Connection(this)
            val session = call.sessions.get<ConnectionToUser>()

            if (session == null) {
                close(CloseReason(CloseReason.Codes.NORMAL, "User not authorized"))
            } else {
                call.sessions.set(session.copy(connectionId = thisConnection.id, userId = session.userId))
            }
            //Some code
}

但我无法在 webSocket 中设置会话。

【问题讨论】:

  • 获取当前连接,你使用Connection(this)有什么原因吗? WebSocketSession 接口的docs 在这里可能很有用,您可以在webSocket { ... } 中调用this.call
  • 我需要能够在websocket {...}以外的其他地方访问当前的Web套接字会话,因此,我将来使用Connection(this)通过Web套接字发送数据。

标签: kotlin websocket ktor


【解决方案1】:

您可以使用并发映射将用户会话存储在内存中。下面是代码示例:

typealias UserId = Int

fun main() {
    val sessions = ConcurrentHashMap<UserId, WebSocketServerSession>()

    embeddedServer(CIO, port = 7777) {
        install(WebSockets)
        routing {
            webSocket("/auth") {
                val userId = 123
                sessions[userId] = this
            }

            webSocket("/") {
                val userId = 123
                val session = sessions[userId]

                if (session == null) {
                    close(CloseReason(CloseReason.Codes.NORMAL, "User not authorized"))
                } else {
                    println("Session does exist")
                }
            }
        }
    }.start(wait = true)
}

这个解决方案的灵感来自answer

【讨论】:

    最近更新 更多