【发布时间】:2016-09-05 00:15:43
【问题描述】:
我的 I/O 流程如下:
- 客户端向通道发送数据#1
- server(handler)根据客户端数据从数据库接收数据并发送给客户端
- 客户端将数据#2 发送到通道
- server(handler)根据客户端数据再次从数据库中接收数据并发送回客户端并关闭通道
如果第一次读取通道时间过长,ReadTimeoutHandler 会按预期触发异常。但是,如果第一次读取正常(= 足够快)并且第二次读取通道花费的时间太长,则不会抛出 TimeoutException 并且处理程序等待 5 分钟直到它关闭通道。似乎 ReadTimeoutHandler 仅适用于通道中的第一次读取。是否有可能让 ReadTimeoutHandler 在通道中进行多次读取?
使用的 Netty 版本:4.0.12
公共类 MyServer {
private static final class MyInitializer extends ChannelInitializer<SocketChannel> {
...
@Override
public void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(
new ReadTimeoutHandler(5, TimeUnit.SECONDS),
new MyHandler(server, serverConnection));
}
...
}
}
公共类 MyHandler 扩展 SimpleChannelInboundHandler {
private static final Logger LOG = LoggerFactory.getLogger(MyHandler.class);
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
Message message = database.getMessage(msg);
ChannelFuture operation = ctx.writeAndFlush(message)
if (message.isEnd()) operation.addListener(new CloseConverstationListener(ctx));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
if (cause instanceof ReadTimeoutException) {
LOG.error("ReadTimeoutException");
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
}
private class CloseConverstationListener implements GenericFutureListener<ChannelFuture> {
private final ChannelHandlerContext ctx;
private CloseConverstationListener(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@Override
public void operationComplete(ChannelFuture future) throws Exception {
future.channel().close().sync();
}
}
}
【问题讨论】:
-
您确定发布了完整的管道吗?没有完成从字节到字符串的对话。