danny.lesnik
danny.lesnik

Reputation: 18639

Write to channel on Read Time out

I would like to write time out error whenever I catch Reader Idle time out.

public class TimeOutHandler extends IdleStateAwareChannelHandler {

      @Override
         public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) {
             if (e.getState() == IdleState.READER_IDLE) {
                 System.out.println("Reader TimeOut");
                    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
                    response.setHeader(Names.CONTENT_TYPE, "application/json; charset=UTF-8");
                    response.setContent(ChannelBuffers.copiedBuffer("{\"timeout\":true}", CharsetUtil.UTF_8));
                     ChannelFuture future = e.getChannel().write(response);
                     future.addListener(ChannelFutureListener.CLOSE);
             } 
         }
}

The handler is working but nothing is written to the channel. Is such scenario possible?

Update:

My pipeline factory:

public class AsyncServerPipelineFactory implements ChannelPipelineFactory {

    static HashedWheelTimer timer = new HashedWheelTimer();

    private final ChannelHandler idleStateHandler = new IdleStateHandler(timer, 10, 20, 0);
    public ChannelPipeline getPipeline() throws Exception {
        ChannelPipeline pipeline = Channels.pipeline( idleStateHandler,new TimeOutHandler());
     pipeline.addLast("decoder", new HttpRequestDecoder());
     pipeline.addLast("encoder", new HttpResponseEncoder());
     pipeline.addLast("handler", new HTTPRequestHandler());
    return pipeline;
    }
}

Upvotes: 2

Views: 432

Answers (1)

Nino Walker
Nino Walker

Reputation: 2903

Your pipeline is misconfigured. Any handler that writes an HttpResponse must be inserted after your HttpResponseEncoder. e.g.

 ChannelPipeline pipeline = Channels.pipeline();
 pipeline.addLast("idler", idleStateHandler);
 pipeline.addLast("decoder", new HttpRequestDecoder());
 pipeline.addLast("encoder", new HttpResponseEncoder());
 pipeline.addLast("timer-outer", new TimeOutHandler());
 pipeline.addLast("handler", new HTTPRequestHandler());

Upvotes: 1

Related Questions