Netty:关于“丢弃”Netty示例的writeindex

时间:2013-01-27 08:50:59

标签: netty

这是netty源包中的一个例子,我打印了writeindex, 我测试了一个客户端,我想知道

public class DiscardClientHandler extends SimpleChannelUpstreamHandler {
...
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
    // Send the initial messages.
    generateTraffic(e);
}
@Override
public void channelInterestChanged(ChannelHandlerContext ctx, ChannelStateEvent e) {
    // Keep sending messages whenever the current socket buffer has room.
    generateTraffic(e);
}

private void generateTraffic(ChannelStateEvent e) {
    // Keep generating traffic until the channel is unwritable.
    // A channel becomes unwritable when its internal buffer is full.
    // If you keep writing messages ignoring this property,
    // you will end up with an OutOfMemoryError.
    Channel channel = e.getChannel();
    while (channel.isWritable()) {
        ChannelBuffer m = nextMessage();
        if (m == null) {
            break;
        }
        channel.write(m);
    }
}

以上是clint代码......

public class DiscardServerHandler extends SimpleChannelUpstreamHandler {
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    // Discard received data silently by doing nothing.
ChannelBuffer cb = (ChannelBuffer) e.getMessage();
    transferredBytes += cb.readableBytes();

    System.out.println("-=-=- " + transferredBytes + "-=-" + cb.writerIndex() + "-=- " + e.getMessage().toString());
    }
-=-=- 679039232-=-65536-=- BigEndianHeapChannelBuffer(ridx=0, widx=65536, cap=65536)
-=-=- 679072768-=-33536-=- BigEndianHeapChannelBuffer(ridx=0, widx=33536, cap=33536)
-=-=- 679105792-=-33024-=- BigEndianHeapChannelBuffer(ridx=0, widx=33024, cap=33024)
...
-=-=- 679298816-=-256-=- BigEndianHeapChannelBuffer(ridx=0, widx=256, cap=256)
-=-=- 679299072-=-256-=- BigEndianHeapChannelBuffer(ridx=0, widx=256, cap=256)
-=-=- 679299328-=-256-=- BigEndianHeapChannelBuffer(ridx=0, widx=256, cap=256)
...
-=-=- 679600640-=-65536-=- BigEndianHeapChannelBuffer(ridx=0, widx=65536, cap=65536)
-=-=- 679634176-=-33536-=- BigEndianHeapChannelBuffer(ridx=0, widx=33536, cap=33536)
-=-=- 679640576-=-6400-=- BigEndianHeapChannelBuffer(ridx=0, widx=6400, cap=6400)
....

我测试了一个客户端,我想知道:

  1. 为什么writeIndex有时是256,有时是65536?
  2. 为什么最大的是65536?
  3. private ChannelBuffer nextMessage(){return ChannelBuffers.wrappedBuffer(content); //内容大小为256} 我希望一个客户端使用相同的通道缓冲区,一个writeindex增加序列?我对吗?

1 个答案:

答案 0 :(得分:1)

这取决于读操作能够“读取”多少数据。所以它可以一直不同。 65536是64k,这很可能是应用程序的RECV_BUF大小,因此它是“最大”。