Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Netty client, how to get a response back from a request sent to the server

Tags:

netty

I'm trying to piece together a Netty client. I need to send a request to a server (that I don't control) and I'm expecting a response back.

I'm not exactly sure how to get the response back.

So if i had:

ChannelFuture future = bootstrap.connect(new InetSocketAddress("foo.com", 1654));
Channel connector = future.awaitUninterruptibly().getChannel();
ChannelFuture response = connector.write(query);

How do i get the response data out of the response ChannelFuture? Do i need to add a ChannelHandler to the bootstrap pipeline? If so, how do i associate the response to the request?

Thanks,

like image 584
Eric Weinberg Avatar asked Oct 10 '22 05:10

Eric Weinberg


2 Answers

Firstly, you might refer to sample of localtime. In handler of "LocalTimeClientHandler", you can find the trick of blocking request/response.

But this is still a "hello world" showcase project, so there are still 2 issues we need to consider:

  1. The idea in this sample is to send a batch once and get back a response once. So it's not suitable for production pattern to send continuously by reusing the same channel.

  2. If you want to send the requests and get back the right responses as soon as possible with heavy load, you need to refactor the queue a little bit more otherwise the performance is really poor.

like image 55
Bright Avatar answered Oct 13 '22 10:10

Bright


Yeah you need to add a ChannelHandler. The simplest way in your case would be to extend SimpleChannelUpstreamHandler and overwrite the channelConnected(…) method and the messageReceived(…) method. In channelConnected you would fire up the Channel.write(…) and in messageReceived you receive the response. If the responses can come in in different order then the writes you need to write your own handling code.

Another solution would be to add a SimpleChannelUpstreamHandler to the pipeline before you call write. Something like this:

channel.getPipeline().addLast("yourHandlerName", new SimpleChannelUpstreamHandler()) {
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        // remove handler after receiving response
        ctx.getPipeline().remove(this);

         // do logic
         ...
      }
});
like image 40
Norman Maurer Avatar answered Oct 13 '22 11:10

Norman Maurer