【发布时间】:2017-01-09 05:04:47
【问题描述】:
我读过Netty Guide,它对ChannelFuture 的解释不多。我发现 ChannelFuture 在应用时是一个复杂的想法。
我要做的是在初始响应后将消息写入上下文。不同于典型的请求/响应流。我需要这样的流程:
- 客户端发送请求 -> 服务器(netty)
- 服务器使用 ctx.writeAndFlush(msg); 发送响应
- 在第 2 步完成后,服务器会向该 ctx 发送更多消息。
问题是,如果我这样做,第二次写入将不会发送出去:
ctx.writeAndFlush(response);
Message newMsg = createMessage();
ctx.writeAndFlush(newMsg); //will not send to client
然后我尝试使用ChannelFuture,它可以工作,但我不确定我是否逻辑正确:
ChannelFuture msgIsSent = ctx.writeAndFlush(response);
if(msgIsSent.isDone())
{
Message newMsg = createMessage();
ctx.writeAndFlush(newMsg); //this works
}
还是应该使用 ChannelFutureListener() 代替?
ChannelFuture msgIsSent = ctx.writeAndFlush(response);
msgIsSent.addListener(new ChannelFutureListener(){
@Override
public void operationComplete(ChannelFuture future)
{
Message newMsg = createMessage();
ctx.writeAndFlush(newMsg);
}
});
这也有效吗?
哪一种是最佳实践方法?使用方法2有什么潜在的问题吗?
【问题讨论】: