向 netty 服务器发出请求时,不会调用 ChannelRead 方法

ChannelRead method is not getting invoked when a request is made for netty server

我正在实现一个接受 http 请求并执行一些业务逻辑的 netty 服务器 基本上,我在 localhost/hello 和 sysout uri is hello

上接受 GET 请求

当我 运行 服务器时,我没有在 CustomRequestHandler#channelRead0 方法中看到任何系统输出。 我让调试器保持打开状态,但我看到没有调用 channelRead0 方法。 我不知道是什么问题

我使用的是 Netty 4.1.30.Final 版本

public class HttpServer {

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

        InetSocketAddress tcpSocketAddress = new InetSocketAddress(8080);

        System.out.println("Starting http server at " + tcpSocketAddress.getPort());
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

        ServerBootstrap bootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new MyChannelInitializer())
                .childOption(ChannelOption.AUTO_READ, false);


        ChannelFuture serverChannelFuture = bootstrap.bind(tcpSocketAddress).sync();
        System.out.println("open the browser");
        serverChannelFuture.channel().closeFuture().sync();
        } finally {
             bossGroup.shutdownGracefully();
             workerGroup.shutdownGracefully();
        }
    }
}


public class MyChannelIntializer extends ChannelInitializer<SocketChannel> {

    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new LoggingHandler(LogLevel.INFO));
        //p.addLast(new HttpServerCodec());
        p.addLast(new HttpRequestDecoder());
        p.addLast(new HttpResponseEncoder());
        p.addLast(new CustomRequestHandler());
    }
}

public class CustomRequestHandler extends SimpleChannelInboundHandler<Object> {

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object httpObject) {
        System.out.println("hello world");
        if (httpObject instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) httpObject;
            System.out.println("uri is " + request.getUri());
    }
}

问题是你使用了:

                .childOption(ChannelOption.AUTO_READ, false);

这意味着一旦通道被接受,它将不会处理任何传入数据,直到您每次要处理更多入站数据时调用 ctx.read()

所以您的选择是删除此行或覆盖 CustomRequestHandler 中的 channelActive(...) 并在那里调用 ctx.read()。这将确保您将尝试读取一些入站数据。也就是说,当您想要处理更多数据时,您将需要再次调用 ctx.read()