ktor 中的当前网络套接字会话

Current web socket session in ktor

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

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 中设置会话。

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

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