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

Mic*_*mid 5 tcp netty

我有一个关于在netty TCP服务器上配置超时的问题.现在,我像这样设置连接时间:

serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 20000);
Run Code Online (Sandbox Code Playgroud)

这似乎有效,一切都很好.现在我想知道是否可以在服务器端定义"读取超时".想法是当读取超时过去时服务器工作线程被中断,以便它可用于其他任务.当我尝试按如下方式设置读取超时时,我在启动时收到"不支持的通道选项"警告:

serverBootstrap.childOption(ChannelOption.SO_TIMEOUT, 30000);
Run Code Online (Sandbox Code Playgroud)

有没有办法在服务器端实现"读/处理超时"?任何帮助表示赞赏.

亲切的问候,迈克尔

Moh*_*-Aw 6

添加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());
...
Run Code Online (Sandbox Code Playgroud)