java - 为什么在 Netty 用户指南中调用 ctx.write() 后没有调用 ctx.flush()?
问题描述
在netty
Java 文档中是这样说的so be sure to call flush() once you want to request to flush
,但在这个例子中它说没有必要调用ctx.flush()
. 但我没有发现flush(ChannelHandlerContext ctx)
被称为如它所说的那样。
package io.netty.example.time;
public class TimeEncoder extends ChannelOutboundHandlerAdapter {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
UnixTime m = (UnixTime) msg;
ByteBuf encoded = ctx.alloc().buffer(4);
encoded.writeInt((int)m.value());
ctx.write(encoded, promise); // (1)
}
}
Second, we did not call ctx.flush(). There is a separate handler method void flush(ChannelHandlerContext ctx) which is purposed to override the flush() operation.
https://netty.io/wiki/user-guide-for-4.x.html#wiki-h3-8
解决方案
缓冲的重点是你将一堆数据“收集”在一起并一次发送,因为发送大量数据的速度与发送少量数据的速度大致相同(因为 IO 很慢)。
这是分配一个 4 字节的缓冲区。如果您每 4 个字节刷新一次,则效率不会很高。
在某个地方会有一个刷新,只是不是在这个特定的方法中。
推荐阅读
- powershell - 将变量传递给函数
- reactjs - 如何从打字稿文件中导出 React 组件
- powershell - Powershell 在 VS Code 终端中的行为与普通终端不同
- php - PHP Benchmarking - 内置 min() 函数似乎很慢
- javascript - 使用 Regex 和 Javascript 从字符串中获取基本 url
- github - 使用 API 获取 Github Enterprise Stats
- tensorflow - ValueError:输入 0 与层 conv1d_1 不兼容:预期 ndim=3,发现 ndim=2
- android - 反应原生。错误:文件名必须以 .xml 或 .png 结尾
- c# - ELMAH 不记录从 ASP.NET MVC Ajax.BeginForm 引发的异常
- python - 如何在管道中重新采样文本(不平衡组)?