在netty通道上设置套接字超时

Rom*_*man 16 netty

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

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

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

谢谢

小智 15

如果使用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));
...
Run Code Online (Sandbox Code Playgroud)

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

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