在 Netty 客户端处理来自服务器的响应 [英] Handling response from server in Netty client

查看:60
本文介绍了在 Netty 客户端处理来自服务器的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Netty 编写 JavaFX 应用程序来实现自定义协议.没有会话状态,但我想将服务器响应与特定的出站请求相关联(并将结果返回到正确的 JavaFX Task.)到目前为止我还没有能够这样做客户端代码,因为 responseFuture 是一个 ChannelFuture.

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());
        }
    }
});

我尝试查看如何配置 PipeLine 以某种方式安装 ChannelHandlers 以在共享上下文变量中共享信息,但我找不到任何重要的信息.

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.

任何人都可以建议我可以用 Netty 中的响应完成"的 UI 任务的惯用位置吗?

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

推荐答案

Netty 无法为您做这样的工作,因为它无法理解配对机制.在客户端,您需要实现 ChannelHandler 并将初始值设定项传递给 .handler(handler) 方法.有关详细信息,请参阅 Netty TimeClient 示例.在处理程序中,channelRead 方法处理来自服务器的响应,对其进行反序列化,并根据特定于您的应用程序对的机制与之前创建的 Future 并完成它.Future 不一定是 Netty 的未来,因为这部分完全不在 Netty 处理中.

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.

对于配对,我假设您使用一些发送到服务器的 id,服务器将相同的 id 发送回客户端.所以在这种情况下,一些 Map 就足够了.

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.

这篇关于在 Netty 客户端处理来自服务器的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆