package com.jsowell.pile.rpc; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; public class RpcClient { public Channel connect(String host, Integer port) { EventLoopGroup worker = new NioEventLoopGroup(); Channel channel = null; try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(worker) .channel(NioSocketChannel.class) .option(ChannelOption.AUTO_READ, true) .handler(new ClientChannelInitializer()); ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); System.out.println("客户端启动"); channel = channelFuture.channel(); // 添加关闭监听器 channel.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { System.out.println("关闭客户端"); worker.shutdownGracefully(); } }); } catch (Exception e) { e.printStackTrace(); if(channel == null || !channel.isActive()) { worker.shutdownGracefully(); } else { channel.close(); } } return channel; } }