netty - 在 TCP 服务器上配置超时

netty - configure timeouts on TCP server

我有一个关于在 netty TCP 服务器上配置超时的问题。现在,我这样设置 connect timout

serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 20000);

这似乎有效,一切顺利。现在我想知道是否可以在服务器端定义一个 "read timeout" 。这个想法是当读取超时结束时服务器工作线程被中断,以便它可以用于其他任务。当我尝试如下设置读取超时时,我在启动时收到 "unsupported channel option" 警告:

serverBootstrap.childOption(ChannelOption.SO_TIMEOUT, 30000);

有没有办法在服务器端实现 "read/processing timeout"?感谢任何帮助。

亲切的问候, 迈克尔

ReadTimeoutHandler 添加到管道的第一个位置:

http://netty.io/4.0/api/io/netty/handler/timeout/ReadTimeoutHandler.html

public class ReadTimeoutHandler extends ChannelInboundHandlerAdapter

// Raises a ReadTimeoutException when no data was read within a certain period of time.

// The connection is closed when there is no inbound traffic
// for 30 seconds.

public class MyChannelInitializer extends ChannelInitializer<Channel> {
    public void initChannel(Channel channel) {
        channel.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(30);
        channel.pipeline().addLast("myHandler", new MyHandler());
    }
}

// Handler should handle the ReadTimeoutException.
public class MyHandler extends ChannelDuplexHandler {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        if (cause instanceof ReadTimeoutException) {
            // do something
        } else {
            super.exceptionCaught(ctx, cause);
        }
    }
}

ServerBootstrap bootstrap = ...;
...
bootstrap.childHandler(new MyChannelInitializer());
...