Nettyチャネルにソケットタイムアウトを設定します

StackOverflow https://stackoverflow.com/questions/3726696

  •  03-10-2019
  •  | 
  •  

質問

ネットワンチャネルがあり、基礎となるソケットにタイムアウトを設定したいと思います(デフォルトで0に設定されています)。

タイムアウトの目的は、たとえば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));
...

それがタイムアウトを引き起こす場合、myhandler.exceptioncaught(channelhandlercontext ctx、ExceptionEvent e)は readtimeoutexception.

@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
    if (e.getCause() instanceof ReadTimeoutException) {
        // NOP
    }
    ctx.getChannel().close();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top