基于Netty实现静态web服务器

基于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());  
    }
}

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

/**
 * 绑定处理程序中的简单通道
 * 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都已经获取到!
           DefaultFullHttpResponse response = new DefaultFullHttpResponse();
           ctx.channel().writeAndFlush(response);
        }
    }

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

}

推荐一个我的项目:

基于Netty实现可自动渲染HTML页面的静态Web服务器


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值