netty.io客户端没有发送请求正文

时间:2014-05-14 10:01:18

标签: netty

我有以下简单的代码。它一直工作到三月,但现在我突然看到它工作了 到达服务器端的请求没有任何正文...来自客户端代码我可以看到即使是简单的文本也不会... 我在我的应用程序中使用netty.io -all 4.0.10 jar,我的客户端代码如下:

请帮忙

public class HttpClient {

    private final URI uri;
    private final String ip;
    private final int port;


    public void run() {
        System.out.println("In run method of HttpClient!!!!!!!!!!!!"+uri);
        String scheme = uri.getScheme() == null? "http" : uri.getScheme();
        String host = uri.getHost() == null? "localhost" : uri.getHost();
        System.out.println("--------------------A------------------------------");

        if (!"http".equalsIgnoreCase(scheme) ) {
            System.err.println("Only HTTP is supported.");
            return;
        }
        System.out.println("---------------------B----------------------------------");
        // Configure the client.
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .handler(new HttpClientInitializer());

            // Make the connection attempt.
            Channel ch = b.connect(host, port).sync().channel();

          //  StringBuilder fileData = new StringBuilder("xmlToBePushed");

            ByteBuf      reqContent=Unpooled.copiedBuffer("HELLOOOOOOOOOOOOOOOOOOOOO",CharsetUtil.US_ASCII);
            System.out.println(host+"::"+port+"-->Sending dprules xml "+reqContent.toString());
            // Prepare the HTTP request.
            HttpRequest request = new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath(),reqContent);
            request.headers().set(HttpHeaders.Names.HOST, host);
            request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
            request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
            request.headers().set("IP", this.ip+":"+port);

            // Send the HTTP request.
            ch.writeAndFlush(request);
           // ch.write(request);

            // Wait for the server to close the connection.
            ch.closeFuture().sync();
        } catch (Exception ex){
            System.out.println("EXCEPTION!!!!!!!!!!!!!!!!!!"+ex.getMessage());
        } finally {
            // Shut down executor threads to exit
            System.out.println("Client is shuttingdown gracefully..");
            group.shutdownGracefully();
        }
    }

}

服务器服务器处理程序是:

public class HnrServerHandler extends SimpleChannelInboundHandler<Object> {
    private final StringBuilder buf = new StringBuilder();    // File content for infra. Same content as bufForUi + ip added as first line
    private final StringBuilder bufForUi=new StringBuilder(); // file content for UI to pick with no IP in it.
    private HttpRequest request;
    FullHttpResponse response;

    private String ipAddress=null;

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("In channelRead0 of HnrServerHandler..........");
        ipAddress = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress();
        int port = ((InetSocketAddress)ctx.channel().remoteAddress()).getPort();

        System.out.println("request is coming from ipAddress :"+ipAddress +", port :"+port);
        System.out.println("*******"+msg.toString());
        if (msg instanceof HttpRequest) {

            HttpRequest request = this.request = (HttpRequest) msg;

            if (!request.getDecoderResult().isSuccess()) {
                sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
                return;
            }

            if (request.getMethod() != POST) {
                sendHttpResponse(ctx, request, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
                return;
            }

        }



        System.out.println("Check if HttpContent......");
        if (msg instanceof HttpContent) {
            System.out.println("ITs HttpContent......");
            HttpContent httpContent = (HttpContent) msg;
            ByteBuf content = httpContent.content();

            buf.append(content.toString(CharsetUtil.UTF_8));

            System.out.println("...........0...............");
            System.out.println("........"+buf.toString());
            buf.delete(0, buf.length());
            bufForUi.delete(0, bufForUi.length());
            if (msg instanceof LastHttpContent) {
                LastHttpContent trailer = (LastHttpContent) msg;
                writeResponse(trailer, ctx);
            }
        }

        return;
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("In cannel read complete!!!");
        ctx.flush();
    }

    private static void sendHttpResponse(
           ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
        System.out.println("In send http response!!!");

        // Generate an error page if response getStatus code is not OK (200).
        if (res.getStatus().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
            buf.release();
        }

        // Send the response and close the connection if necessary.
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!isKeepAlive(req) || res.getStatus().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("In exceptionCaught..........");
        cause.printStackTrace();
        ctx.close();
    }
    private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
        System.out.println("In write Response method of HnrServerHandler........");
        // Decide whether to close the connection or not.
        boolean keepAlive = isKeepAlive(request);
         response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.getDecoderResult().isSuccess()? OK : BAD_REQUEST);

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

        if (keepAlive) {
            response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }
        // Write the response.
        ctx.write(response);

        return keepAlive;
    }    
}

当我看到日志时,身体部分/消息丢失。

我刚刚使用了netty客户端/服务器的标准方式。我不确定为什么它不起作用。我在这里遗漏了什么,请告诉我。

1 个答案:

答案 0 :(得分:4)

我缺少内容长度标题。一旦我添加它,问题就得到了解决。