When building a server using Netty, you may want to use FIN and RST properly depending on the situation when closing Channel (socket). For example, there is a requirement that FIN (RST when delayed timeout) is set normally, but RST is set immediately when an abnormality is detected.
Whether to use FIN / RST when Channel is closed can be specified when building ServerBootstrap.
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(0);
ServerBootstrap bootstrap = new ServerBootstrap()
    .option(ChannelOption.SO_BACKLOG, 1024)
    .group(bossGroup, workerGroup)
    .channel(NioServerSocketChannel.class)
    .childOption(ChannelOption.SO_LINGER, 10) //FIN → Delayed timeout(10 seconds)→ Specify to close with RST
    .childHandler(new MyChannelInitializer());
// ...
NOTE:
Release by RST that specifies> -1 is disabled.
If you want to close the ServerBootstrap in a way different from the default behavior specified when building it, you can do so by getting the ChannelConfig from the Channel and changing the SO_LINGER setting.
@ChannelHandler.Sharable
class MyHandler extends SimpleChannelInboundHandler<byte[]> {
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, byte[] msg) {
    // ...
  }
  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    ctx.channel().config().setOption(ChannelOption.SO_LINGER, 0); //Specify to close with RST immediately
    ctx.close();
  }
}
Recommended Posts