🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ // 标记一个ChannelHandler被多个Channel安全共享 @ChannelHandler.Sharable public class EchoServerHandler extends ChannelInboundHandlerAdapter { /** * 每个传入的消息都要调用 */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; System.out.println("server : "+ in.toString(CharsetUtil.UTF_8)); // 接收的消息写给发送者,不冲刷出站 ctx.write(in); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { // 将未决消息冲刷到远程节点,并且关闭该Channel ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 打印异常栈跟踪 cause.printStackTrace(); // 关闭Channel ctx.close(); } } ~~~