• 高强度学习训练第十三天总结:使用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);
        }
    }
    
    
  • 相关阅读:
    函数的调用-转载
    HTML常用标签-手打抄录-来自-烟雨飘零-拜谢
    CSS常用标签-手打抄录-感谢原未知博主-拜谢了
    JS函数表达的几种写法
    JS数组---转及补充--
    标准文档流特性-不含块级元素和行内元素
    块级元素和行内元素-标签收集-区别之处
    CSS盒子知识
    把应用push到/system/app上面后,出现java.lang.UnsatisfiedLinkError的问题
    Vysor:在电脑里控制你的安卓手机
  • 原文地址:https://www.cnblogs.com/godoforange/p/11593295.html
Copyright © 2020-2023  润新知