RequestHandler is not invoked in Netty server

brain storm :

I am working on Netty Http server. I have handlers created and registered. But I do not see the request hitting the handler

Here is the main 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");
        }

    }
}

I do not see "hello" printed in console when I invoke localhost:8080/calculate?a=1&b=2

what is wrong here?

Ferrybig :

Your issue is caused by missing handlers in your pipeline.

At your moment, you only have 2 handlers in your pipeline:

  • HttpMessageHandler, that handles FullHttpRequest objects
  • CalculatorOperationHandler, that handles Operation objects

When data from the browser comes in, it comes in as a ByteBuf object, but you don't handle this object!

To convert from a ByteBuf to a FullHttpRequest, you need to add other handlers in your pipeline that can do this.

The first handler you need is HttpServerCodec, this class converts ByteBuf objects into objects that are parts of an HTTP exchange, like headers, trailing headers an request bodies.

Then you need to add a HttpObjectAggregator, that combines the above objects into a FullHttpRequest, so you only have to deal with 1 object.

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

You could also add a new LoggingHandler(LogLevel.INFO) if you want to see the traffic between any layer.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=144312&siteId=1