企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
~~~ public class TextWebsocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { Channel channel = ctx.channel(); channelGroup.forEach(ch -> { if (ch != channel){ ch.writeAndFlush(new TextWebSocketFrame(channel.id().asLongText() + " 发送消息: "+ msg.text() + "\n")); }else { ch.writeAndFlush(new TextWebSocketFrame("自己: "+ msg.text() + "\n")); } }); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); channelGroup.writeAndFlush(new TextWebSocketFrame(ctx.channel().id().asLongText() + " 加入\n")); channelGroup.add(channel); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { channelGroup.writeAndFlush(new TextWebSocketFrame(ctx.channel().id().asLongText() + " 离开\n")); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channelGroup.writeAndFlush(new TextWebSocketFrame(ctx.channel().id().asLongText() + " 上线\n")); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("异常"); cause.printStackTrace(); ctx.close(); } } ~~~