I have a netty client that connect to remote server for a request-response cycle. I want to block till the remote connection is successful and I have parsed the response.
Here is what I do
Channel ch = bootstrap.connect(addr).sync().channel();
ChannelFuture f = ch.writeAndFlush(obj);
f.sync();
f.channel().close();
System.out.println("hello world");
On my handler
MyHandler extends ChannelInboundHandlerAdapter {
static Map<String,Object> = new HashMap<>();
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
System.out.println("foo bar");
if (msg instanceof FullHttpResponse) {
parseAndPutInMap(msg);
}
ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
what I observed is calling f.sync() is not blocking. I see "hello world" printed right away before "foo bar". I also navigated through the debugger and did not see channelRead hit right after f.sync() is called.
so what is wrong here? I want this operation to be blocking since I need to process response before I decide what to do.
Your operation is actually blocking, it waits till "writing" has been finished.
But this is a problem for you, as you want to wait till "reading" has been finished.
One of the things you could do is "syncing" on the close future of the channel, and then close the channel in your read handler when you are done reading.