问题
I need to push a big file to client, but I want to limit the speed(such as 100Kb/s), how to use ChannelTrafficShapingHandler?
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 100)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(
new StringEncoder(CharsetUtil.UTF_8),
new LineBasedFrameDecoder(8192),
new StringDecoder(CharsetUtil.UTF_8),
new ChannelTrafficShapingHandler(1,1,10L),
new ChunkedWriteHandler(),
new FileServerHandler()
);
}
});
This demo doesn't work, why?
回答1:
Did you manage the channel write capability in your FileServerHandler ?
As stated in Netty API for ChannelTrafficShapingHandler
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().
You shall also consider to have object size in read or write operations relatively adapted to the bandwidth you required: for instance having 10 MB objects for 10KB/s will lead to burst effect, while having 100 KB objects for 1 MB/s should be smoothly handle by this TrafficShaping handler.
And the initialization:
- First item is Write limit in B/s (Here 1 is strongly not recommended, something close to 1024 is minimal, for 1KB/s)
- second item is Read limit in B/S (Here 1 is strongly not recommended, something close to 1024 is minimal, for 1KB/s, or 0 for no limit)
- First item is interval check in ms (Here 1L means every ms, which is strongly not recommended, something close to 1000 is minimal, for every 1s)
You can see an example (using Discard example) here, in particular:
- for the server initialization
- for the client handler part (which is similar to the server handler part) on how to use channel writability
来源:https://stackoverflow.com/questions/34326230/how-to-use-channeltrafficshapinghandler-in-netty-4