高强度学习训练第十三天总结:使用Netty实现一个http服务器

Posted godoforange

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了高强度学习训练第十三天总结:使用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);
    }
}

以上是关于高强度学习训练第十三天总结:使用Netty实现一个http服务器的主要内容,如果未能解决你的问题,请参考以下文章

马哥教育M28第十三天到第十五天学习总结

Java基础第十三天总结

IT十八掌掌第十三天课程总结

Web前端学习第十三天·fighting_HTML页面设计技巧总结

python学习第十三天 迭代器 生成器

记账本开发记录——第十三天(2020.1.31)