1. public class LineBaseClientHandler 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. ctx.close();
    8. }
    9. /*** 客户端被通知channel活跃后,做事*/
    10. @Override
    11. public void channelActive(ChannelHandlerContext ctx) throws Exception {
    12. ByteBuf msg = null;
    13. String request = "Mark,Lison,King,James,Deer"
    14. + System.getProperty("line.separator");
    15. for(int i=0;i<10;i++){
    16. msg = Unpooled.buffer(request.length());
    17. msg.writeBytes(request.getBytes());
    18. ctx.writeAndFlush(msg);
    19. }
    20. }
    21. /*** 发生异常后的处理*/
    22. @Override
    23. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    24. cause.printStackTrace();
    25. ctx.close();
    26. }
    27. }