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(); }}
EchoClientHandler
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { //读取到网络数据后进行业务处理 @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { System.out.println("client Accept"+msg.toString(CharsetUtil.UTF_8)); //ctx.close(); ctx.close(); } //channel活跃后,做业务处理 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.copiedBuffer( "Hello,Netty",CharsetUtil.UTF_8)); }}