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,
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:
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.
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.
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
...
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With