netty 客户端中的 io.netty.util.IllegalReferenceCountException

io.netty.util.IllegalReferenceCountException in netty client

提问人:cobalt17 提问时间:11/7/2023 更新时间:11/7/2023 访问量:21

问:

请帮我解决以下问题,我编写了一个同步netty客户端,当我尝试发送请求时,出现错误:

java.util.concurrent.CompletionException:io.netty.util.IllegalReferenceCountException:refCnt:0 为什么会出现此错误? netty 客户端和服务器如下所示:


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.util.CharsetUtil;

import java.io.File;

public class HttpsServerExample {

    public static void main(String[] args) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                             pipeline.addLast("codec", new HttpServerCodec());
                            pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
                            pipeline.addLast("handler", new HttpRequestHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(9991).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
            System.out.println(request);
            System.out.println("content: " + request.content().toString(CharsetUtil.UTF_8));
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            response.content().writeBytes("{\"key\": \"response\"}".getBytes(CharsetUtil.UTF_8));
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
            ChannelFuture future = ctx.writeAndFlush(response);
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.util.CharsetUtil;

import java.io.File;
import java.net.URI;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class SynchronousNettyHttpsClient {

    public static CompletableFuture<FullHttpResponse> sendHttpsRequest(HttpRequest request, String host, int port, String path) throws InterruptedException {
        CompletableFuture<FullHttpResponse> future = new CompletableFuture<>();
        EventLoopGroup group = new NioEventLoopGroup();
        try {

            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                             ch.pipeline().addLast(new HttpClientCodec());
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpResponse>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) {
                                    System.out.println(response);
                                    future.complete(response);
                                    System.out.println("response content: " + response.content().toString(CharsetUtil.UTF_8));
                                    ctx.close();
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                    future.completeExceptionally(cause);
                                    System.out.println("exceptionCaught");
                                    ctx.close();
                                }
                            });
                        }
                    });

            Channel channel = b.connect(host, port).sync().channel();


            channel.writeAndFlush(request);
            channel.closeFuture().sync();
         } catch (Exception e) {
            future.completeExceptionally(e);
        } finally {
            group.shutdownGracefully();
        }
        return future;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        String jsonContent = "{\"key\": \"request\"}";
        ByteBuf content = Unpooled.copiedBuffer(jsonContent, CharsetUtil.UTF_8);
        DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
        request.content().writeBytes(content);
        request.headers().set(HttpHeaderNames.HOST, "localhost"); // Set the host header
        request.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json"); // Set the content type
        request.headers().set(HttpHeaderNames.CONTENT_LENGTH,  content .readableBytes()); // Set the content length
        CompletableFuture<FullHttpResponse> responseFuture = sendHttpsRequest(request,"localhost", 9991, "/");
        responseFuture.thenAccept(response -> {
            System.out.println(response);
            ByteBuf content1 = response.content();
            String responseBody = content1.toString(CharsetUtil.UTF_8);
        }).exceptionally(ex -> {
            ex.printStackTrace();
            System.err.println("Request failed: " + ex.getMessage());
            return null;
        });
    }
}

你能解释一下我做错了什么吗?

编写程序同步 netty 客户端

Java Netty

评论

1赞 PMF 11/8/2023
请具体说明错误发生的确切位置。
0赞 cobalt17 11/13/2023
我找到了问题所在。它包括这样一个事实,即在发送请求时,计数器会减少。要重用请求对象,您需要通过调用 retain() 来提高计数器值。方法

答: 暂无答案