package cn.flightfeather.supervision.socket
|
|
import org.springframework.web.socket.WebSocketSession
|
import java.io.IOException
|
import java.util.concurrent.ConcurrentHashMap
|
|
/**
|
*
|
* @date 2024/7/19
|
* @author feiyu02
|
*/
|
object WsSessionManager {
|
/**
|
* 保存连接 session 的地方
|
*/
|
private val SESSION_POOL = ConcurrentHashMap<String, WebSocketSession>()
|
|
/**
|
* 添加 session
|
*
|
* @param key
|
*/
|
fun add(key: String, session: WebSocketSession) {
|
// 添加 session
|
SESSION_POOL[key] = session
|
}
|
|
/**
|
* 删除 session,会返回删除的 session
|
*
|
* @param key
|
* @return
|
*/
|
fun remove(key: String?): WebSocketSession? {
|
// 删除 session
|
return SESSION_POOL.remove(key)
|
}
|
|
/**
|
* 删除并同步关闭连接
|
*
|
* @param key
|
*/
|
fun removeAndClose(key: String?) {
|
val session: WebSocketSession? = remove(key)
|
if (session != null) {
|
try {
|
// 关闭连接
|
session.close()
|
} catch (e: IOException) {
|
// todo: 关闭出现异常处理
|
e.printStackTrace()
|
}
|
}
|
}
|
|
/**
|
* 获得 session
|
*
|
* @param key
|
* @return
|
*/
|
operator fun get(key: String?): WebSocketSession? {
|
// 获得 session
|
return SESSION_POOL[key]
|
}
|
|
fun eachSession(action:(session:WebSocketSession) -> Unit) {
|
SESSION_POOL.forEachEntry(10){
|
action(it.value)
|
}
|
}
|
}
|