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. }