Skip to content

Commit 81f4991

Browse files
committed
fix(WS): disconnect with deadlock
1 parent dd5c1fc commit 81f4991

2 files changed

Lines changed: 21 additions & 5 deletions

File tree

src/main/kotlin/net/ccbluex/netty/http/HttpServer.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ class HttpServer {
122122
suspend fun stop() = lock.withLock {
123123
logger.info("Shutting down Netty server...")
124124
try {
125-
webSocketController?.disconnect()
125+
webSocketController?.disconnectAsync()
126126
serverChannel?.close()?.awaitSuspend()
127127
bossGroup?.shutdownGracefully()?.awaitSuspend()
128128
workerGroup?.shutdownGracefully()?.awaitSuspend()

src/main/kotlin/net/ccbluex/netty/http/websocket/WebSocketController.kt

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import kotlinx.coroutines.asCoroutineDispatcher
3030
import kotlinx.coroutines.cancel
3131
import kotlinx.coroutines.joinAll
3232
import kotlinx.coroutines.launch
33+
import kotlinx.coroutines.supervisorScope
3334
import net.ccbluex.netty.http.HttpServer.Companion.logger
3435
import net.ccbluex.netty.http.coroutines.syncSuspend
3536
import java.nio.channels.ClosedChannelException
@@ -100,10 +101,25 @@ class WebSocketController(
100101
* Closes all active contexts.
101102
*/
102103
fun disconnect() {
103-
activeContexts.removeIf { handlerContext ->
104-
runCatching {
105-
handlerContext.channel().close().sync()
106-
}.isSuccess
104+
val contexts = activeContexts.toTypedArray()
105+
activeContexts.clear()
106+
107+
contexts.forEach { handlerContext ->
108+
handlerContext.channel().close().sync()
109+
}
110+
}
111+
112+
/**
113+
* Closes all active contexts async.
114+
*/
115+
suspend fun disconnectAsync() = supervisorScope {
116+
val contexts = activeContexts.toTypedArray()
117+
activeContexts.clear()
118+
119+
contexts.forEach { handlerContext ->
120+
launch {
121+
handlerContext.channel().close().syncSuspend()
122+
}
107123
}
108124
}
109125

0 commit comments

Comments
 (0)