1. public class DelimiterEchoClient {
    2. private final String host;
    3. public DelimiterEchoClient(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,DelimiterEchoServer.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. ByteBuf delimiter = Unpooled.copiedBuffer(
    25. DelimiterEchoServer.DELIMITER_SYMBOL.getBytes());
    26. ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,
    27. delimiter));
    28. ch.pipeline().addLast(new DelimiterClientHandler());
    29. }
    30. }
    31. public static void main(String[] args) throws InterruptedException {
    32. new DelimiterEchoClient("127.0.0.1").start();
    33. }
    34. }