- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已阅读 Netty Guide ,ChannelFuture上就不多解释了。我发现 ChannelFuture 在应用时是一个复杂的想法。
我想做的是在初始响应后将消息写入上下文。与典型的请求/响应流程不同。我需要这样的流程:
问题是,如果我这样做,第二次写入将不会发送出去:
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有潜在的问题吗?
最佳答案
当然,这也取决于您的“协议(protocol)”(也就是说,例如,如果您使用 HTTP,则 HTTP 协议(protocol)不支持为同一请求发送 2 个答案)。但是假设您的协议(protocol)允许您发送多个响应部分:
Netty 添加消息发送到管道,遵守顺序。
所以在你的第一个例子中,我有点惊讶它不起作用:
ctx.writeAndFlush(response);
Message newMsg = createMessage();
ctx.writeAndFlush(newMsg); // should send the message
但是它可能由您的协议(protocol)引导。例如,这可能会发生:
response in message queue to send
flush not yet done
newMsg in message queue to send
flush now come but protocol does not support 2 messages so only send first one
因此,如果您的协议(protocol)必须承认第一条消息已发送,那么您必须等待第一条消息,因此请执行以下操作:
ctx.writeAndFlush(response).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (future.isDone()) {
Message newMsg = createMessage();
ctx.writeAndFlush(newMsg);
} else { // an error occurs, do perhaps something else
}
}
});
所以你的最后一个建议(我只是没有创建 ChannelFuture 而是直接使用 writeAndFlush 的结果,但两者是相等的)。请注意操作完成并不意味着成功的情况。
关于java - Netty ChannelFuture 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39269388/
下面是《Netty in Action》一书中的一些代码片段。 我想知道如果连接操作在 1 之后和 2 之前完成,ChannelFutureListener 是否有机会收到通知? 最佳答案 检查 Ne
我已阅读 Netty Guide ,ChannelFuture上就不多解释了。我发现 ChannelFuture 在应用时是一个复杂的想法。 我想做的是在初始响应后将消息写入上下文。与典型的请求/响应
我正在使用Netty 4.0为我的硕士论文创建分布式隐私保护算法。我使用 TDD,大多数时候,由于 Netty 的模块化 API,它的效果非常好。上周我遇到的一个问题是我不知道如何测试依赖于 Chan
在 Netty 4 中,写操作的 ChannelFuture(假设是 NioSocketChannel)究竟何时会“完成”? Netty 是否等待 ACK 数据包? ChannelPipeline 中
是否可以在不创建不必要的 ChannelFuture 的情况下写入 Netty channel ? (不为 GC 生成不必要的对象...) 最佳答案 如果你真的不想创建一个ChannelFuture,
我有一个 channel 需要保持打开状态,因为写入了大量消息,并且我不想为每次写入都进行 SSL 握手。 如果我这样做: ChannelFuture future = channel.writeAn
我正在尝试使用 the following code这是 Netty Nio 中网络套接字的实现。我已经实现了一个 JavaFx Gui,我想从 Gui 中读取从服务器或其他客户端接收到的消息。 Ne
我是一名优秀的程序员,十分优秀!