0

这是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);
    }
}

以上是克林特代码...

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?

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

4

1 回答 1

1

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

于 2013-01-27T10:23:35.797 回答