【发布时间】:2014-05-29 19:35:35
【问题描述】:
我基于 netty 4 编写了一个 REST 服务器。客户端处理程序如下所示。
netty 提供的 msg 中的 bytebuffer 容量不同。当客户端消息大于缓冲区时,消息将被拆分。我发现每个片段都会调用 channelRead 和 ChannelReadComplete 。我通常看到的是 ByteBuf 在 512 左右,消息在 600 左右。我得到前 512 个字节的 channelRead,然后是 ChannelReadComplete ,然后是剩余 100 字节的另一个 channelRead 和他们的 channelReadComplete - 2 条消息而不是 1 条。
我在这里找到了一些相关的问题,但我想知道 channelReadComplete 有什么意义?它真的在每个 channelRead 之后调用吗?只要有可用的字节,难道不应该在调用 channelReadComplete 之前读入它们吗?
public class ClientHandler extends ChannelInboundHandlerAdapter {
....
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
Report.debug("Read from client");
ByteBuf buf = (ByteBuf) msg;
String contents = buf.toString(io.netty.util.CharsetUtil.US_ASCII);
ReferenceCountUtil.release(msg);
ClientConnection client = ClientConnection.get(ctx);
if (client != null) {
client.messageText(contents); // adds text to buffer
return;
}
((parse serial number from contents, process registration))
ClientConnection.online(serialNumber, ctx); // register success, create the client object
}
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ClientConnection client = ClientConnection.get(ctx);
if (client == null)
Report.debug("completed read of message from unregistered client");
else {
Report.debug("completed read of message from client " + client.serialNumber());
String contents = client.messageText();
... ((process message))
}
}
}
【问题讨论】: