1. @ChannelHandler.Sharable
    2. public class LineBaseServerHandler extends ChannelInboundHandlerAdapter {
    3. private AtomicInteger counter = new AtomicInteger(0);
    4. @Override
    5. public void channelActive(ChannelHandlerContext ctx) throws Exception {
    6. System.out.println("客户端:["+ctx.channel().remoteAddress()+"]已连接.........");
    7. }
    8. /*** 服务端读取到网络数据后的处理*/
    9. @Override
    10. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    11. ByteBuf in = (ByteBuf)msg;
    12. String request = in.toString(CharsetUtil.UTF_8);
    13. System.out.println("Server Accept["+request
    14. +"] and the counter is:"+counter.incrementAndGet());
    15. String resp = "Hello,"+request+". Welcome to Netty World!"
    16. + System.getProperty("line.separator");
    17. ctx.writeAndFlush(Unpooled.copiedBuffer(resp.getBytes()));
    18. }
    19. /*** 服务端读取完成网络数据后的处理*/
    20. @Override
    21. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    22. //ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    23. }
    24. /*** 发生异常后的处理*/
    25. @Override
    26. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    27. cause.printStackTrace();
    28. ctx.close();
    29. }
    30. @Override
    31. public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    32. System.out.println(ctx.channel().remoteAddress()+"即将关闭...");
    33. }
    34. }