Handling response from server in Netty client

2019-08-11 14:22发布

问题:

I'm writing a JavaFX application using Netty to implement a custom protocol. There is no session state but I would like to correlate a server response to a particular outbound request (and return the result to the correct JavaFX Task.) So far I haven't been able to do so in the client code, because the responseFuture is a ChannelFuture<Void>.

future = tcpBoostrap.connect(address, 3333).sync();
final Channel channel = future.awaitUninterruptibly().channel();

ChannelFuture responseFuture = channel.writeAndFlush(requestBuilder.build());
responseFuture.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if (channelFuture.isSuccess()) {
            logger.debug("completed operation: {}", channelFuture.toString());
        }
    }
});

I tried looking how to configure a PipeLine to somehow install ChannelHandlers that would share the information in a shared context variable but I could not find anything significant.

Can anyone suggest the idiomatic place where I can stuff the UI Task that I can "complete" with the response in Netty?

回答1:

Netty can't do such work for you as it cannot understand pairing mechanism. On the client side you need to implement ChannelHandler and pass the initializer to the .handler(handler) method. See Netty TimeClient example for details. In the handler channelRead method process the response from the server, deserialize it and according to the mechanism specific to your application pair with previously created Future and complete it. The Future doesn't need to be necessarily Netty future as this part is completely out of Netty processing.

For the pairing I assume you use some id which you send to the server and server sends the same id back to the client. So in such case some Map<Long, Future<?>> would be sufficient.



标签: java netty