多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
~~~ 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(); } } ~~~