0

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

Netty - How to get server response in the client

How to get server response with netty client

brain storm
  • 30,124
  • 69
  • 225
  • 393
  • Netty is design for asynchronous high performance scenario, if you only want a HTTP client perform synchronize request, maybe Apache HTTP client is more conveniently (especially HTTP Chunk Stream) – Derek J. May 24 '19 at 01:24
  • @DerekJ. Thanks for the suggestion. I know about HTTP Client. our usecases are different. we already use Netty. – brain storm May 24 '19 at 05:56

0 Answers0