Netty应用示例(三)http应用示例

Netty对Http提供了非常丰富的支持,让我们可以针对自己的需求实现需要的Http服务器。

1、HttpServer实现

HttpServer实现源码:

public class HttpServer {

    public static void main(String[] args){
        HttpServer.startServer(9999);
    }


    public static void startServer(int port){
        //负责接收客户端连接
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        //处理连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(boosGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline channelPipeline = ch.pipeline();

                            //负载http 请求编码解码
                            channelPipeline.addLast(new HttpServerCodec());

                            //实际处理请求
                            channelPipeline.addLast(new HttpRequestHandler());

                        }
                    });

            //绑定端口号
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();

        }catch(Exception e){
            e.printStackTrace();
        }finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();

        }
    }

}

Http协议的编解码主要由HttpServerCodec实现。

2、HttpRequestHandler实现

HttpRequestHandler实现源码:

public class HttpRequestHandler extends SimpleChannelInboundHandler {

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception {
        if(httpObject instanceof HttpRequest){
            HttpRequest request = (HttpRequest) httpObject;
            System.out.println("接收到请求:  "+ request.method() + ",url=" + request.uri());

            //设置返回内容
            ByteBuf content = Unpooled.copiedBuffer("Hello World\n", CharsetUtil.UTF_8);

            //创建响应
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,content);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes() + "");

            ctx.writeAndFlush(response);
        }
    }
}

3、测试结果

3.1、启动服务器:

打开浏览器,输入以下url:http://127.0.0.1:9999/test/http?name=zhaozhou

3.2、服务端日志如下:

服务端输出.png

3.3、浏览器显示如下:

浏览器输出.png

3.4、实现源码:https://github.com/zhaozhou11/netty-demo.git

你可能感兴趣的:(Netty应用示例(三)http应用示例)