Netty 4 学习--服务端handler收不到消息
/用Netty4写一个传送文件的组件。学习过程中出现一个bug
1.首先构造服务端 Handler
ServerHandler extends ChannelInboundHandlerAdapter
public void channelRead(ChannelHandlerContext ctx, Object msg) { System.out.println("Server received:" + msg); ctx.write(msg); } public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }
接下来构造客户端 Handler
ClientHandler extends SimpleChannelInboundHandler<ByteBuf>
public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("FileClient conn a server"); ctx.write(Unpooled.copiedBuffer("HELO,I'm a client", CharsetUtil.UTF_8)); System.out.println("FileClient write complete"); } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { System.out.println("FileClient channelRead0" + msg); System.out.println("Client received:" + ByteBufUtil.hexDump( msg.readBytes(msg.readableBytes()))); }
最后运行发现,服务端根本收不到消息,这也是Netty In Action 中的EchoServer的源码。
最后找到bug,原来在channelActive中需要加入ctx.flush(),服务端才能接收到消息。
而服务端之所以需要用ChannelInboundHandlerAdapter是因为在异步的读写中,需要持有消息一段时间。