0

我有一个调用 Netty 服务器的 Apache 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 Server 的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中测试两者。

4

1 回答 1

0

我认为您需要设置 CONTENT_LENGTH 标头,否则,因为您使用的是持久连接,客户端将不知道何时读取了整个响应。就像是

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

于 2013-10-30T11:17:26.123 回答