1. @ChannelHandler.Sharable
    2. public class MsgPackServerHandler extends ChannelInboundHandlerAdapter {
    3. private AtomicInteger counter = new AtomicInteger(0);
    4. /*** 服务端读取到网络数据后的处理*/
    5. @Override
    6. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    7. //将上一个handler生成的数据强制转型
    8. User user = (User)msg;
    9. System.out.println("Server Accept["+user
    10. +"] and the counter is:"+counter.incrementAndGet());
    11. //服务器的应答
    12. String resp = "I process user :"+user.getUserName()
    13. + System.getProperty("line.separator");
    14. ctx.writeAndFlush(Unpooled.copiedBuffer(resp.getBytes()));
    15. ctx.fireChannelRead(user);
    16. }
    17. /*** 发生异常后的处理*/
    18. @Override
    19. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    20. cause.printStackTrace();
    21. ctx.close();
    22. }
    23. }