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

 书友73428983 发布于 2023-01-15 11:30

我有以下简单的代码。它一直工作到三月,但是突然之间我看到它在工作。到达服务器端的请求没有任何内容...从客户端代码中,我可以看到即使是简单的文本也不会运行...我正在使用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 {
    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客户/服务器的标准方法。我不确定为什么它不起作用。我在这里想念什么吗让我知道。

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有