[color=blue][size=medium]在netty里面,messageReceived的实现如下:
[/size][/color][code="java"]
Object m = e.getMessage();
if (!(m instanceof ChannelBuffer)) {
ctx.sendUpstream(e);
return;
}
ChannelBuffer input = (ChannelBuffer) m;
if (!input.readable()) {
return;
}
ChannelBuffer cumulation = cumulation(ctx);
if (cumulation.readable()) {
cumulation.discardReadBytes();
cumulation.writeBytes(input);
callDecode(ctx, e.getChannel(), cumulation, e.getRemoteAddress());
} else {
callDecode(ctx, e.getChannel(), input, e.getRemoteAddress());
if (input.readable()) {
cumulation.writeBytes(input);
}
}
[/code]
[color=blue][size=medium]我们看到比较关键的是cumulation函数,函数如下:
[/size][/color][code="java"]
private ChannelBuffer cumulation(ChannelHandlerContext ctx) {
ChannelBuffer c = cumulation;
if (c == null) {
c = ChannelBuffers.dynamicBuffer(
ctx.getChannel().getConfig().getBufferFactory());
cumulation = c;
}
return c;
}
[/code]
[color=blue][size=medium]在这个里面为什么要这么实现呢,什么时候cumulation不为空呢?
我们再看看上面的实现:[/size][/color]
[code="java"]
if (cumulation.readable()) {
cumulation.discardReadBytes();
cumulation.writeBytes(input);
callDecode(ctx, e.getChannel(), cumulation, e.getRemoteAddress());
} else {
callDecode(ctx, e.getChannel(), input, e.getRemoteAddress());
if (input.readable()) {
cumulation.writeBytes(input);
}
}
[/code]
[color=blue][size=medium]这个if和else里面的逻辑应该怎么理解。
[/size][/color]