RequestHandler 未在 Netty 服务器中调用

RequestHandler is not invoked in Netty server

我正在开发 Netty Http 服务器。我创建并注册了处理程序。但我没有看到请求命中处理程序

这里是主要内容class

public class NettyServer {

    private int port;

    private NettyServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8080;
        }
        new NettyServer(port).run();
    }

    private void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new HttpMessageHandler(),new CalculatorOperationHandler());
                }
            }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}

HttpMessageHandler.java

public class HttpMessageHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        System.out.println("hello");
        String uri = msg.uri();
        HttpMethod httpMethod = msg.method();
        HttpHeaders headers = msg.headers();

        if (HttpMethod.GET == httpMethod) {

            String[] uriComponents = uri.split("[?]");
            String endpoint = uriComponents[0];
            String[] queryParams = uriComponents[1].split("&");

            if ("/calculate".equalsIgnoreCase(endpoint)) {

                String[] firstQueryParam = queryParams[0].split("=");
                String[] secondQueryParam = queryParams[1].split("=");

                Integer a = Integer.valueOf(firstQueryParam[1]);
                Integer b = Integer.valueOf(secondQueryParam[1]);
                String operator = headers.get("operator");

                Operation operation = new Operation(a, b, operator);
                ctx.fireChannelRead(operation);
            }
        } else {
            throw new UnsupportedOperationException("HTTP method not supported");
        }

    }
}

当我调用 localhost:8080/calculate?a=1&b=2

时,我没有在控制台中看到 "hello"

这里有什么问题?

您的问题是由管道中缺少处理程序引起的。

目前,您的管道中只有 2 个处理程序:

  • HttpMessageHandler,处理 FullHttpRequest objects
  • CalculatorOperationHandler,处理 Operation objects

当来自浏览器的数据进来时,它以 ByteBuf object 的形式进来,但你不处理这个 object!

要从 ByteBuf 转换为 FullHttpRequest,您需要在管道中添加其他可以执行此操作的处理程序。

您需要的第一个处理程序是 HttpServerCodec,此 class 将 ByteBuf object 转换为 object,它们是 HTTP 交换的一部分,像 headers,尾随 headers 个请求主体。

然后你需要添加一个HttpObjectAggregator,将上面的object组合成一个FullHttpRequest,所以你只需要处理1个object。

ch.pipeline().addLast(
    new HttpServerCodec(),
    new HttpObjectAggregator(65536), // Handle POST/PUT requests up 64KB
    new HttpMessageHandler(),
    new CalculatorOperationHandler()
);

如果您想查看任何层之间的流量,您还可以添加一个new LoggingHandler(LogLevel.INFO)