0
votes

I have a Apache HttpComponents client which calls a Netty server. The code is a simple test.

   ExecutorService threadpool = Executors.newFixedThreadPool(2);
   Async async = Async.newInstance().use(threadpool);


   Request[] requests = new Request[] {
ContentType.APPLICATION_JSON),
            Request.Post("http://localhost:9090/print").bodyString(getJSon(),    ContentType.APPLICATION_JSON)
   };


    Queue<Future<Content>> queue = new LinkedList<Future<Content>>();
    // Execute requests asynchronously
    for (final Request request: requests) {

        Future<Content> future = async.execute(request, new FutureCallback<Content>() {

            public void failed(final Exception ex) {
                logger.info(ex.getMessage() + ": " + request);
            }

            public void completed(final Content content) {
                logger.info("Request completed: " + request);
            }

            public void cancelled() {
                logger.info("Request cancelled: " + request);
            }

        });
        queue.add(future);
    }

    while(!queue.isEmpty()) {
        Future<Content> future = queue.remove();
        try {

            Content c = future.get();
            logger.info( "Response " + c.asString() );
        } catch (ExecutionException ex) {

            logger.info( "ExecutionException [" + getExceptionAsString( ex ) + "]" );
        }
    }

This is the Netty Server's writeResponse method.

private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {

    boolean keepAlive = isKeepAlive(request);


    Response respond = new Response();
    ByteBuf bufResponse = Unpooled.copiedBuffer( respond.getJSon(),
                                                 CharsetUtil.UTF_8);
    logger.info( "Response is [" + respond.getJSon() + "]" );

    FullHttpResponse response = new DefaultFullHttpResponse(
            HTTP_1_1, currentObj.getDecoderResult().isSuccess()? OK : BAD_REQUEST,
            Unpooled.copiedBuffer(bufResponse.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");

    ctx.writeAndFlush( response );
    return keepAlive;  
}

The calls to the logger work as expected. It is returning a JSON object which I am printing.

But the callback method in the HttpComponents client is not called. It appears that the server does not return to the client.

The Netty server seems to work but I am not sure why the client does not return cleanly. Can anyone help me spot the mistake ? I am testing both in eclipse.

1

1 Answers

0
votes

I think you need to set the CONTENT_LENGTH header otherwise, because you're using persistent connections, the client won't know when it has read the entire response. Something like

response.headers().set(CONTENT_LENGTH, response.content().readableBytes());