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