zoukankan      html  css  js  c++  java
  • Netty入门(三)之web服务器

    【本文版权归微信公众号"代码艺术"(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究。若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!】

    Netty入门(三)之web服务器

    阅读前请参考

    • Netty入门(一)之webSocket聊天室
    • Netty入门(二)之PC聊天室

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

    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请求而言不太方便获取参数。

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

    【本文版权归微信公众号"代码艺术"(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究。若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!】

    /**
     * 绑定处理程序中的简单通道
     * 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();
        }
    
    }
    

    版权声明

    【本文版权归微信公众号"代码艺术"(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究。若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!】

  • 相关阅读:
    算法训练 P1103
    算法训练 表达式计算
    算法训练 表达式计算
    基础练习 时间转换
    基础练习 字符串对比
    Codeforces 527D Clique Problem
    Codeforces 527C Glass Carving
    Codeforces 527B Error Correct System
    Codeforces 527A Glass Carving
    Topcoder SRM 655 DIV1 250 CountryGroupHard
  • 原文地址:https://www.cnblogs.com/onblog/p/13043560.html
Copyright © 2011-2022 走看看