EchoClientHandler

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