Netty入门(三)之web服务器

时间:2023-12-21 23:37:56

Netty入门(三)之web服务器

阅读前请参考

有了前两篇的使用基础,学习本文也很简单!只需要在前两文的基础上稍微改动即可!

Maven依赖

        <!-- Netty -->
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.22.Final</version>
        </dependency>

一:启动类

关于启动类,需要我们做的就是自定义端口以及继承ChannelInitializer类。

/**
 * Netty服务器启动
 * Create by yster@foxmail.com 2018-05-04
 **/
public class HttpServerStartup {
    public void startup() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workGroup);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(new MyServerInitializer());    //继承重写类
            Channel ch = b.bind(8888).sync().channel();    //自定义端口
            ch.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //优雅的退出程序
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

}  

二:信道初始化

/**
 * 信道初始化
 * Create by yster@foxmail.com 2018-05-04
**/
public class MyServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        /**
         * http-request解码器
         * http服务器端对request解码
         */
        pipeline.addLast("decoder", new HttpRequestDecoder());
        /**
         * http-response解码器
         * http服务器端对response编码
         */
        pipeline.addLast("encoder", new HttpResponseEncoder());
        pipeline.addLast("deflater", new HttpContentCompressor());
        pipeline.addLast("handler", new MyServerChannelHandler());
    }
}

值得一提的是,上面信道的处理对post请求而言不太方便获取参数。

三:绑定处理程序中的信道

/**
 * 绑定处理程序中的简单通道
 * Create by yster@foxmail.com 2018-05-04
 **/
@Sharable
public class MyServerChannelHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg){
        if (msg instanceof HttpRequest) {
           //request response都已经获取到!
           ByteBuf byteBuf = Unpooled.copiedBuffer("Hello".getBytes());        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,byteBuf);
           ctx.channel().writeAndFlush(response);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.channel().close();
        cause.printStackTrace();
    }

}