There are few posts around this question. But what I am looking for is quite different.
The netty client will be blocked on server response and proceeds with any business logic after the response is received from server.
Most examples in netty don't show how client recieves response in blocking manner and process them.
I throw around a mutable obj and ask handler to set response object. Here is what I have now, which I feel is hacky
public class MutableObj {
FullHttpResponse response;
}
MutableObj mutable = new MutableObj();
Bootstrap bootstap = new Bootstrap()
.group(bossGroup())
.channel(NioSocketChannel.class)
.handler(MyChannelInitializer(mutable));
Channel ch = bootstrap.connect(addr).sync().channel();
ChannelFuture f = ch.writeAndFlush(obj);
f.sync();
ch.closeFuture().sync();
//since connection was blocked, I will have response object populated
FullHttpResonse response = mutable.getResponse();
//now process the response
MyHandler extends ChannelInboundHandlerAdapter {
MutableObj obj;
public MyHandler(MutableObj obj) {
this.obj=obj;
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
System.out.println("foo bar");
if (msg instanceof FullHttpResponse) {
obj.setResponse((FullHttpResponse) msg);
}
// The following line automatically closes the channel:
ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
}
public class MyChannelIntializer extends ChannelInitializer<SocketChannel> {
private MutableObj obj;
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new HttpClientCodec());
p.addLast(new HttpObjectAggregator(1024 * 1024, true));
p.addLast(new MyHandler(obj));
}
}
The above solution of mine sounds hacky and it is not thred-safe. what is the right way to do here?
Relevant posts I went through
Handling response from server in Netty client