2

How can i get current web socket session? I had an idea to do something like this:

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
}

But i cant set sessions in webSocket.

Sabadon
  • 68
  • 6
  • To get the current connection, is there a reason why you use `Connection(this)`? The [docs](https://ktor.io/docs/websocket.html#WebSocketSession) for the interface of WebSocketSession may be useful here where you can call `this.call` inside `webSocket { ... }` – caladeve Mar 04 '21 at 04:00
  • I need to be able to access the current web socket session in other places than `websocket {...}` Therefore, I use `Connection(this)` to send data over a web socket in the future. – Sabadon Mar 04 '21 at 08:07

1 Answers1

1

You can use a concurrent map to store user sessions in memory. Here is the code example:

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

This solution was inspired by that answer.

Aleksei Tirman
  • 4,658
  • 1
  • 5
  • 24