@@ -21,7 +21,7 @@ package net.ccbluex.netty.http.websocket
2121
2222import io.netty.channel.ChannelHandlerContext
2323import io.netty.handler.codec.http.websocketx.TextWebSocketFrame
24- import io.netty.handler.codec.http.websocketx.WebSocketFrame
24+ import java.util.concurrent.CopyOnWriteArrayList
2525
2626/* *
2727 * Controller for handling websocket connections.
@@ -32,7 +32,7 @@ class WebSocketController {
3232 * Keeps track of all connected websocket connections to the server.
3333 * This is used to broadcast messages to all connected clients.
3434 */
35- val activeContexts = mutableListOf <ChannelHandlerContext >()
35+ private val activeContexts = CopyOnWriteArrayList <ChannelHandlerContext >()
3636
3737 /* *
3838 * Broadcasts a message to all connected clients.
@@ -53,10 +53,30 @@ class WebSocketController {
5353 /* *
5454 * Closes all active contexts.
5555 */
56- fun closeAll () {
57- activeContexts.forEach { handlerContext ->
58- handlerContext.channel().close()
56+ fun disconnect () {
57+ activeContexts.removeIf { handlerContext ->
58+ runCatching {
59+ handlerContext.channel().close().sync()
60+ }.isSuccess
5961 }
6062 }
6163
64+ /* *
65+ * Adds a new context to the list of active contexts.
66+ *
67+ * @param context The context to add.
68+ */
69+ fun addContext (context : ChannelHandlerContext ) {
70+ activeContexts.add(context)
71+ }
72+
73+ /* *
74+ * Removes a context from the list of active contexts.
75+ *
76+ * @param context The context to remove.
77+ */
78+ fun removeContext (context : ChannelHandlerContext ) {
79+ activeContexts.remove(context)
80+ }
81+
6282}
0 commit comments