EchoServerHandler

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