@@ -22,6 +22,7 @@ package net.ccbluex.netty.http.websocket
2222import io.netty.channel.ChannelHandlerContext
2323import io.netty.handler.codec.http.websocketx.TextWebSocketFrame
2424import 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