码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2019-09-27 18:55:48      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:完成   inbound   orange   code   rri   tps   今天   pre   ini   

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服务器

标签:完成   inbound   orange   code   rri   tps   今天   pre   ini   

原文地址:https://www.cnblogs.com/godoforange/p/11593295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!