【发布时间】: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套接字发送数据。