Skip to content

Commit c5508e6

Browse files
committed
WebSocketController broadcast onFailure type change
1 parent 578fb58 commit c5508e6

1 file changed

Lines changed: 11 additions & 7 deletions

File tree

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

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ package net.ccbluex.netty.http.websocket
2222
import io.netty.channel.ChannelHandlerContext
2323
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame
2424
import java.util.concurrent.CopyOnWriteArrayList
25+
import java.util.function.BiConsumer
2526

2627
/**
2728
* Controller for handling websocket connections.
@@ -38,15 +39,18 @@ class WebSocketController {
3839
* Broadcasts a message to all connected clients.
3940
*
4041
* @param text The message to broadcast.
41-
* @param failure The action to take if a failure occurs.
42+
* @param onFailure The action to take if a failure occurs.
4243
*/
43-
fun broadcast(text: String, failure: (ChannelHandlerContext, Throwable) -> Unit = { _, _ -> }) {
44+
fun broadcast(text: String, onFailure: BiConsumer<ChannelHandlerContext, Throwable>? = null) {
4445
val frame = TextWebSocketFrame(text)
45-
activeContexts.forEach { handlerContext ->
46-
try {
47-
handlerContext.channel().writeAndFlush(frame.retainedDuplicate())
48-
} catch (e: Throwable) {
49-
failure(handlerContext, e)
46+
for (handlerContext in activeContexts) {
47+
val channelFuture = handlerContext.channel().writeAndFlush(frame.retainedDuplicate())
48+
if (onFailure != null) {
49+
channelFuture.addListener {
50+
if (!it.isSuccess) {
51+
onFailure.accept(handlerContext, it.cause())
52+
}
53+
}
5054
}
5155
}
5256
frame.release()

0 commit comments

Comments
 (0)