[英]Channel not closing after timeout in netty
I want to close the channel when it hasn't received any data after certain seconds. 我想在某些秒钟后没有收到任何数据的情况下关闭该通道。 I tried IdleHandler, but it isn't working.
我尝试了IdleHandler,但无法正常工作。 My main handler is clientHandler which extends SimpleChannelInboundHandler.
我的主要处理程序是clientHandler,它扩展了SimpleChannelInboundHandler。 This sends data in string and receives data in String format.
这将以字符串形式发送数据,并以字符串格式接收数据。 Sometimes, I don't get the data during that time I want my channel to close after certain timeout, but currently it is waiting for the data from the server.
有时,我希望在某个超时后关闭通道,但在这段时间内没有获取数据,但是当前它正在等待服务器中的数据。
One more observation, When I check in the packet sender to verify for the same request. 另一个观察结果是,当我签入数据包发送者以验证相同的请求时。 I get empty response from the server but this response is not received by my ClientHandler.
我从服务器收到空响应,但ClientHandler未收到此响应。
Following is the code. 以下是代码。
clientBootstrap.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch){
ch.pipeline()
.addLast(new IdleStateHandler(5, 5, 10))
.addLast(new MyHandler())
.addLast(new ClientHandler(cardIssueRequest,promise));
}
});
MyHandler: MyHandler的:
public class MyHandler extends ChannelDuplexHandler {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
if (e.state() == IdleState.READER_IDLE) {
ctx.close();
} else if (e.state() == IdleState.WRITER_IDLE) {
ctx.close();
}
}
}
}
ClientHandler: ClientHandler中:
public class ClientHandler extends SimpleChannelInboundHandler {
RequestModel request;
private final Promise<String> promise;
public ClientHandler(RequestModel request, Promise<String> promise) {
this.request = request;
this.promise = promise;
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) {
String response = ((ByteBuf) o).toString(CharsetUtil.UTF_8);
log.info("Client received: " + response);
promise.trySuccess(response);
}
@Override
public void channelActive(ChannelHandlerContext channelHandlerContext) {
log.info("Client sent: " + request);
channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer((request.toString()), CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause) {
cause.printStackTrace();
channelHandlerContext.close();
promise.setFailure(cause);
}
}
After taking the thread dump, I found the issue was that my program was waiting in the promise statement. 进行线程转储后,我发现问题是我的程序正在promise语句中等待。 So, after setting timeout for the promise, my issue got solved.
因此,在为承诺设置超时后,我的问题解决了。
promise.get(60, TimeUnit.SECONDS)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.