EchoClient
public class EchoClient { private final int port; private final String host; public EchoClient(int port, String host) { this.port = port; this.host = host; } public void start() throws InterruptedException { //线程组 EventLoopGroup group = new NioEventLoopGroup(); try { //客户端启动必须 final Bootstrap b = new Bootstrap();; //将线程组传入 b.group(group) //指定使用NIO进行网络传输 .channel(NioSocketChannel.class) //配置要连接服务器的ip地址和端口 .remoteAddress(new InetSocketAddress(host,port)) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new EchoClientHandler()); } }); // 异步连接服务器,阻塞直到连接完成 ChannelFuture f = b.connect().sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } } public static void main(String[] args) throws InterruptedException { new EchoClient(9999,"127.0.0.1").start(); }}