zoukankan      html  css  js  c++  java
  • 高强度学习训练第十三天总结:使用Netty实现一个http服务器

    Netty入门

    Netty的重要性不言而喻。那么今天就来学习一下Netty。

    整个项目基于Gradle搭建。
    Build如下所示:

    plugins {
        id 'java'
    }
    
    group 'cn.baldorange'
    version '1.0'
    
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
    repositories {
        mavenCentral()
    }
    
    dependencies {
        compile group: 'io.netty', name: 'netty-all', version: '4.1.41.Final'
    }
    
    

    主要得去mvn仓库里把netty-all拉下来。

    一个HTTP的服务器。

    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.buffer.*;
    import io.netty.channel.*;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.codec.http.*;
    import io.netty.util.CharsetUtil;
    
    
    public class TestServer {
        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 ch){
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("httpServerCodec",new HttpServerCodec());
                            pipeline.addLast("httpServerHandler",new SimpleChannelInboundHandler<HttpObject>(){
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception{
                                   if(msg instanceof HttpRequest) {
                                       HttpRequest httpRequest = (HttpRequest) msg;
                                       ByteBuf content = Unpooled.copiedBuffer("Hello World", 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);
                                   }
                                }
                        });
                    }
                });
                ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
                channelFuture.channel().closeFuture().sync();
            }finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    
    }
    
    

    运行结果如下所示:

    好的我们现在已经完成了一个Http最简单的服务器。
    如果跑起来了,我们开始下一步的学习。

    这里面我们可以看到在这俩个地方,我们实现了俩个抽象类

    我们一一去讲解。

    SimpleChannelInboundHandler

    我们新创建一个类,叫HttpServerHandler

    代码如下:

    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    import io.netty.handler.codec.http.*;
    import io.netty.util.CharsetUtil;
    
    public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
            if(msg instanceof HttpRequest) {
                HttpRequest httpRequest = (HttpRequest) msg;
                ByteBuf content = Unpooled.copiedBuffer("Hello World", 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);
            }
        }
    
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel active");
            super.channelActive(ctx);
        }
    
        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel registered");
            super.channelRegistered(ctx);
        }
    
        @Override
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            System.out.println("handle added");
            super.handlerAdded(ctx);
        }
    
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel inactive");
            super.channelInactive(ctx);
        }
    
        @Override
        public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
            System.out.println("channel unregistered");
            super.channelUnregistered(ctx);
        }
    }
    
    
  • 相关阅读:
    day31-python之内置函数
    day30-python之socket
    day28-python之property
    day27-python之迭代器协议
    day26-python之封装
    day25-python之继承组合
    初识AJAX
    写博客的心得
    web前端常见面试题
    学习网络安全的网站
  • 原文地址:https://www.cnblogs.com/godoforange/p/11593295.html
Copyright © 2011-2022 走看看