EchoClient

  1. public class EchoClient {
  2. private final int port;
  3. private final String host;
  4. public EchoClient(int port, String host) {
  5. this.port = port;
  6. this.host = host;
  7. }
  8. public void start() throws InterruptedException {
  9. //线程组
  10. EventLoopGroup group = new NioEventLoopGroup();
  11. try {
  12. //客户端启动必须
  13. final Bootstrap b = new Bootstrap();;
  14. //将线程组传入
  15. b.group(group)
  16. //指定使用NIO进行网络传输
  17. .channel(NioSocketChannel.class)
  18. //配置要连接服务器的ip地址和端口
  19. .remoteAddress(new InetSocketAddress(host,port))
  20. .handler(new ChannelInitializer<SocketChannel>() {
  21. @Override
  22. protected void initChannel(SocketChannel ch) throws Exception {
  23. ch.pipeline().addLast(new EchoClientHandler());
  24. }
  25. });
  26. // 异步连接服务器,阻塞直到连接完成
  27. ChannelFuture f = b.connect().sync();
  28. f.channel().closeFuture().sync();
  29. } finally {
  30. group.shutdownGracefully().sync();
  31. }
  32. }
  33. public static void main(String[] args) throws InterruptedException {
  34. new EchoClient(9999,"127.0.0.1").start();
  35. }
  36. }

EchoClientHandler

  1. public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
  2. //读取到网络数据后进行业务处理
  3. @Override
  4. protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
  5. System.out.println("client Accept"+msg.toString(CharsetUtil.UTF_8));
  6. //ctx.close();
  7. ctx.close();
  8. }
  9. //channel活跃后,做业务处理
  10. @Override
  11. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  12. ctx.writeAndFlush(Unpooled.copiedBuffer(
  13. "Hello,Netty",CharsetUtil.UTF_8));
  14. }
  15. }