1. package net.xdclass.echo;
    2. import io.netty.bootstrap.Bootstrap;
    3. import io.netty.channel.ChannelFuture;
    4. import io.netty.channel.ChannelInitializer;
    5. import io.netty.channel.EventLoopGroup;
    6. import io.netty.channel.nio.NioEventLoopGroup;
    7. import io.netty.channel.socket.SocketChannel;
    8. import io.netty.channel.socket.nio.NioSocketChannel;
    9. import java.net.InetSocketAddress;
    10. public class EchoClient {
    11. private String host;
    12. private int port;
    13. public EchoClient(String host, int port){
    14. this.host = host;
    15. this.port = port;
    16. }
    17. public void start() throws InterruptedException {
    18. EventLoopGroup group = new NioEventLoopGroup();
    19. try {
    20. Bootstrap bootstrap = new Bootstrap();
    21. bootstrap.group(group)
    22. .channel(NioSocketChannel.class)
    23. .remoteAddress(new InetSocketAddress(host, port))
    24. .handler(new ChannelInitializer<SocketChannel>() {
    25. protected void initChannel(SocketChannel ch) throws Exception {
    26. ch.pipeline().addLast(new EchoClientHandler());
    27. }
    28. });
    29. //连接到服务端,connect是异步连接,在调用同步等待sync,等待连接成功
    30. ChannelFuture channelFuture = bootstrap.connect().sync();
    31. //阻塞直到客户端通道关闭
    32. channelFuture.channel().closeFuture().sync();
    33. }finally {
    34. //优雅退出,释放NIO线程组
    35. group.shutdownGracefully();
    36. }
    37. }
    38. public static void main(String []args) throws InterruptedException {
    39. new EchoClient("127.0.0.1",8080).start();
    40. }
    41. }