1. public class FixedLengthClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    2. private AtomicInteger counter = new AtomicInteger(0);
    3. /*** 客户端读取到网络数据后的处理*/
    4. protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
    5. System.out.println("client Accept["+msg.toString(CharsetUtil.UTF_8)
    6. +"] and the counter is:"+counter.incrementAndGet());
    7. }
    8. /*** 客户端被通知channel活跃后,做事*/
    9. @Override
    10. public void channelActive(ChannelHandlerContext ctx) throws Exception {
    11. ByteBuf msg = null;
    12. for(int i=0;i<10;i++){
    13. msg = Unpooled.buffer(FixedLengthEchoClient.REQUEST.length());
    14. msg.writeBytes(FixedLengthEchoClient.REQUEST.getBytes());
    15. ctx.writeAndFlush(msg);
    16. }
    17. }
    18. /*** 发生异常后的处理*/
    19. @Override
    20. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    21. cause.printStackTrace();
    22. ctx.close();
    23. }
    24. }