Setting socket timeout on netty channel

后端 未结 1 802
小鲜肉
小鲜肉 2021-02-07 09:55

I have a netty channel and I would like to set a timeout on the underlying socket ( it is set by default to 0 ).

The purpose of the timeout is that the not used channel

1条回答
  •  臣服心动
    2021-02-07 10:20

    If ReadTimeoutHandler class is used, the time-out can be controlled.

    Following is a quotation from 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));
    ...
    

    When it will cause a time-out, MyHandler.exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) is called with ReadTimeoutException.

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

    0 讨论(0)
提交回复
热议问题