Netty 通道流量整形问题:channelWritabilityChanged 方法未触发

Netty channel traffic shaping issue : channelWritabilityChanged method not trigger

我想控制数据传输的带宽。 根据 Netty 文档,他们建议:

In your handler, you should consider to use the channel.isWritable() and channelWritabilityChanged(ctx) to handle writability, or through future.addListener(new GenericFutureListener()) on the future returned by ctx.write().

这是我的频道初始化程序源代码:

public class MyChannelInitializer extends ChannelInitializer<Channel>
        {
            private int mode;
            private Server server;
            private String fileName;
            public MyChannelInitializer(Server server, int mode,String fileName)
            {
                this.mode=mode;
                this.server=server;
                this.fileName=fileName;
            }
            @Override
            protected void initChannel(Channel ch) throws Exception 
            {
                if (this.mode==MyFtpServer.RECEIVEFILE)
                {
                    ch.pipeline().addLast(new ChannelTrafficShapingHandler(0L,10240L));  
                    ch.pipeline().addLast(new ReceiveFileHandler(this.fileName,server));
                }
                else
                {
                    ch.pipeline().addLast(new ChannelTrafficShapingHandler(10240L,0L));
                    ch.pipeline().addLast("streamer", new ChunkedWriteHandler()); 
                    ch.pipeline().addLast("handler",new SendFileHandler(this.fileName,server));
                }
            }   
        }

发送文件处理程序源代码如下:

    public class SendFileHandler extends SimpleChannelInboundHandler<ByteBuf> 
    {
        String fileName;
        PassiveServer txServer=null;
        public SendFileHandler(String fileName, PassiveServer txServer)
        {
            this.fileName=fileName;
            this.txServer=txServer;
        }
        public void channelWritabilityChanged(ChannelHandlerContext ctx)throws IOException
        {
            System.out.println("isWritable="+ctx.channel().isWritable());
        }
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws IOException 
        {
            System.out.println("SendFileHandler active");
        }
    }   

你能告诉我为什么我的 SendFileHandler 中的 "channelWritabilityChanged" 方法永远不会触发,只触发 channelActive 方法吗?

我将 SendFileHandler.channelActive 方法更改如下:

public void channelActive(ChannelHandlerContext ctx) throws IOException 
{
    Calendar  startTime;
    System.out.println("SendFileHandler active");
    startTime=Calendar.getInstance();
    ctx.fireChannelWritabilityChanged();
}   

SendFileHandler.channelWritabilityChanged方法仍未触发。 谁能告诉我为什么?

我相信是因为 ChunkedWriteHandler 完成了这项工作,直接考虑了可写性。但是,由于它在 channelWritabilityChanged 中的最后一个代码是:

ctx.fireChannelWritabilityChanged();

您应该更改可写性信号。

但是你发送任何文件吗?因为在你的代码中,没有,因此没有 channelWritabilityChanged 应该被提升,因为似乎根本没有写入......(当然,可写性只发生在写入部分,而不是读取部分)。

你也可以看看