🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ 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(); } } ~~~