https://kotlinlang.org logo
#ktor
Title
# ktor
c

codec

08/14/2020, 8:09 AM
How can one differentiate between the
DefaultWebSocketSession
objects? For example, in my
Application.Kt
class, I have:
Copy code
webSocket("/update") {
        connections += this
        try {
            while (true) {
                when (val frame = incoming.receive()) {
                    is Frame.Text -> {
                        val text = frame.readText()
                        // Send message to all the connections, except the messenger connection.
                        for (conn in connections) {
                            if (conn != this) {
                                conn.outgoing.send(Frame.Text(text))
                            }
                        }
                    }
                }
            }
        } catch (e: ClosedReceiveChannelException) {
            <http://log.info|log.info>("connection closed. ignore.")
        }
        finally {
            connections -= this
        }
    }
}
So, what I’m trying to accomplish works there, in that class, but not elsewhere in other application classes. When I just have a list of connection objects, or
DefaultWebSocketSession
objects?
w

Wilfred

08/14/2020, 9:06 PM
In my case, I send a unique identifier as part of the client’s message to the server. I then keep synchronized map of the identifier and the corresponding connection in an object that can be injected anywhere.
👍 1
c

codec

08/14/2020, 10:46 PM
I created a similar solution, i created a
Map<SessionId,DefaultWebSocketSession>
, injected that where it needed to be for the logic.
👍 1
4 Views