future.channel().closeFuture().sync();後面程式碼不執行
阿新 • • 發佈:2019-01-03
在使用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();