Netty analysis of the Http Service Case

Foreword

Earlier we talked about Netty threading model, there are some features Netty, Netty and the use of a Tcp written a service case, this does, we will combine the knowledge learned earlier, to write a Http service case

Http Service Case

Requirements: Use Netty write a Http server, allows the browser to a normal visit, and the server can return information to the browser.

Server code TCP consistent with the previous one, only in the pipeline the pipe additionally added process http encoder, the decoder (HttpServerCodec), a custom handler is not inherited ChannelInboundHandlerAdapter, but inherited SimpleChannelInboundHandler, see the following code:

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

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        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 socketChannel) throws Exception {
                            // 获取管道对象
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // 添加netty提供的处理http的编码、解码器
                            pipeline.addLast(new HttpServerCodec());
                            // 加入自定义的handler
                            pipeline.addLast(new HttpServerHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        // 判断是不是Http请求
        if(httpObject instanceof HttpRequest){

            // 得到http请求
            HttpRequest httpRequest = (HttpRequest) httpObject;
            // 请求地址信息
            URI uri = new URI(httpRequest.uri());
            System.out.println("request url :" + uri.getPath());

            ByteBuf content = Unpooled.copiedBuffer("hello client", CharsetUtil.UTF_8);
            // 创建http响应对象
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            // 设置响应头
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plan");
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            channelHandlerContext.writeAndFlush(httpResponse);
        }
    }
}

Browser to access the test:
Here Insert Picture Description
you can see, the browser requests a success, and received information server responses.

Published 107 original articles · won praise 19 · views 20000 +

Guess you like

Origin blog.csdn.net/chen_changying/article/details/104154745