在使用netty框架时:
Netty是基于Java NIO的网络通信框架.
public RpcResponse send(RpcRequest request) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel channel)
throws Exception {
// 向pipeline中添加编码、解码、业务处理的handler
channel.pipeline()
.addLast(new RpcEncoder(RpcRequest.class)) //OUT - 1
.addLast(new RpcDecoder(RpcResponse.class)) //IN - 1
.addLast(RpcClient.this); //IN - 2
}
}).option(ChannelOption.SO_KEEPALIVE, true);
// 链接服务器
ChannelFuture future = bootstrap.connect(host, port).sync();
//将request对象写入outbundle处理后发出(即RpcEncoder编码器)
future.channel().writeAndFlush(request).sync();
// 用线程等待的方式决定是否关闭连接
// 其意义是:先在此阻塞,等待获取到服务端的返回后,被唤醒,从而关闭网络连接
synchronized (obj) {
obj.wait();
}
if (response != null) {
//服务器同步连接断开时,这句代码才会往下执行
future.channel().closeFuture().sync();
}
return response;
} finally {
group.shutdownGracefully();
}
}
//也就是服务端执行完这一句:ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
//服务端的这句代码才会往下执行
future.channel().closeFuture().sync();