How to use ChannelTrafficShapingHandler in Netty 4+?

99封情书 提交于 2019-12-08 02:28:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!