LineBaseEchoClient

  1. public class LineBaseEchoClient {
  2. private final String host;
  3. public LineBaseEchoClient(String host) {
  4. this.host = host;
  5. }
  6. public void start() throws InterruptedException {
  7. EventLoopGroup group = new NioEventLoopGroup();/*线程组*/
  8. try {
  9. final Bootstrap b = new Bootstrap();;/*客户端启动必须*/
  10. b.group(group)/*将线程组传入*/
  11. .channel(NioSocketChannel.class)/*指定使用NIO进行网络传输*/
  12. .remoteAddress(new InetSocketAddress(host,LineBaseEchoServer.PORT))/*配置要连接服务器的ip地址和端口*/
  13. .handler(new ChannelInitializerImp());
  14. ChannelFuture f = b.connect().sync();
  15. System.out.println("已连接到服务器.....");
  16. f.channel().closeFuture().sync();
  17. } finally {
  18. group.shutdownGracefully().sync();
  19. }
  20. }
  21. private static class ChannelInitializerImp extends ChannelInitializer<Channel> {
  22. @Override
  23. protected void initChannel(Channel ch) throws Exception {
  24. ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
  25. ch.pipeline().addLast(new LineBaseClientHandler());
  26. }
  27. }
  28. public static void main(String[] args) throws InterruptedException {
  29. new LineBaseEchoClient("127.0.0.1").start();
  30. }
  31. }