2013-10-29 87 views
0

我有一個調用Netty服務器的Apache HttpComponents客戶端。該代碼是一個簡單的測試。Netty服務器和HttpComponents客戶端

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) + "]"); 
     } 
    } 

這是Netty的服務器的 writeResponse方法。

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; 
} 

對記錄器的調用按預期工作。它正在返回一個我正在打印的JSON對象。

但是不調用HttpComponents客戶端中的回調方法。看起來服務器沒有返回到客戶端。

Netty服務器似乎工作,但我不知道爲什麼客戶端不會乾淨地返回。任何人都可以幫我發現錯誤嗎?我正在eclipse中進行測試。

回答

0

我認爲您需要設置CONTENT_LENGTH標頭否則,因爲您使用的是持久連接,客戶端將不知道它何時讀取了整個響應。類似於

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