netty - 在TCP服务器

时间:2016-05-17 08:57:34

标签: tcp netty

我有一个关于在netty TCP服务器上配置超时的问题。现在,我将连接时间设置为:

serverBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 20000);

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

serverBootstrap.childOption(ChannelOption.SO_TIMEOUT, 30000);

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

亲切的问候, 迈克尔

1 个答案:

答案 0 :(得分: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());
...