Netty服务器和HttpComponents客户端

时间:2013-10-29 08:48:18

标签: netty

我有一个Apache HttpComponents客户端,它调用Netty服务器。代码是一个简单的测试。

   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服务器似乎有效,但我不确定为什么客户端不能干净利落地返回。任何人都可以帮我发现错误吗?我正在日食中测试。

1 个答案:

答案 0 :(得分:0)

我认为你需要设置CONTENT_LENGTH标头,因为你正在使用持久连接,客户端不会知道它何时读取了整个响应。像

这样的东西

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