【问题标题】:Setting socket timeout on netty channel在 netty 通道上设置套接字超时
【发布时间】:2010-09-16 12:36:30
【问题描述】:

我有一个 netty 通道,我想在底层套接字上设置一个超时时间(默认设置为 0)。

超时的目的是如果15分钟内没有任何事情发生,那么未使用的频道将被关闭。

虽然我没有看到任何配置可以这样做,而且套接字本身也对我隐藏。

谢谢

【问题讨论】:

    标签: netty


    【解决方案1】:

    如果使用ReadTimeoutHandler类,可以控制超时。

    以下是Javadoc的引用。

    public class MyPipelineFactory implements ChannelPipelineFactory {
        private final Timer timer;
        public MyPipelineFactory(Timer timer) {
            this.timer = timer;
        }
    
        public ChannelPipeline getPipeline() {
            // An example configuration that implements 30-second read timeout:
            return Channels.pipeline(
                new ReadTimeoutHandler(timer, 30), // timer must be shared.
                new MyHandler());
        }
    }
    
    
    ServerBootstrap bootstrap = ...;
    Timer timer = new HashedWheelTimer();
    ...
    bootstrap.setPipelineFactory(new MyPipelineFactory(timer));
    ...
    

    当它会导致超时时,使用 ReadTimeoutException 调用 MyHandler.exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)。

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        if (e.getCause() instanceof ReadTimeoutException) {
            // NOP
        }
        ctx.getChannel().close();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 2018-06-21
      • 2018-10-04
      • 1970-01-01
      • 2012-04-08
      • 2012-04-20
      • 2012-11-12
      相关资源
      最近更新 更多