Netty Github 上@normanmaurer 的回答
你应该使用
Channel.isWritable()
检查“队列”是否已满。如果是这样,您将需要检查是否有足够的空间来写更多。因此,如果您将数据快速写入以将其发送给客户端,则可能会发生您看到的效果。尝试通过 DefaultFileRegion 或 ChunkedFile 写入文件时,您可以解决此类问题。
@normanmaurer 谢谢我错过了频道的这种方法!我想我需要阅读里面发生的事情:
org.jboss.netty.handler.stream.ChunkedWriteHandler
更新:2012/08/30 这是我为解决我的问题而编写的代码:
public class LimitedChannelSpeaker{
Channel channel;
final Object lock = new Object();
long maxMemorySizeB;
long size = 0;
Map<ChannelBufferRef, Integer> buffer2readablebytes = new HashMap<ChannelBufferRef, Integer>();
public LimitedChannelSpeaker(Channel channel, long maxMemorySizeB) {
this.channel= channel;
this.maxMemorySizeB = maxMemorySizeB;
}
public ChannelFuture speak(ChannelBuffer buff) {
if (buff.readableBytes() > maxMemorySizeB) {
throw new IndexOutOfBoundsException("The buffer is larger than the maximum allowed size of " + maxMemorySizeB + "B.");
}
synchronized (lock) {
while (size + buff.readableBytes() > maxMemorySizeB) {
try {
lock.wait();
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
ChannelBufferRef ref = new ChannelBufferRef(buff);
ref.register();
ChannelFuture future = channel.write(buff);
future.addListener(new ChannelBufferRef(buff));
return future;
}
}
private void spoken(ChannelBufferRef ref) {
synchronized (lock) {
ref.unregister();
lock.notifyAll();
}
}
private class ChannelBufferRef implements ChannelFutureListener {
int readableBytes;
public ChannelBufferRef(ChannelBuffer buff) {
readableBytes = buff.readableBytes();
}
public void unregister() {
buffer2readablebytes.remove(this);
size -= readableBytes;
}
public void register() {
buffer2readablebytes.put(this, readableBytes);
size += readableBytes;
}
@Override
public void operationComplete(ChannelFuture future) throws Exception {
spoken(this);
}
}
}