基于Netty的HTTP服务器的实现

目录

 

HTTP协议简介

Http请求消息

Http响应消息

Http服务器实现

    业务处理器

案例


HTTP协议简介

Http协议是基于TCP/IP协议基础上用于超文本传输的应用层协议,主要有以下特点:

  • 支持C/S模式
  • 无状态
  • 灵活
  • 简单,直接在browser中指定url,携带请求参数或请求消息体就可与服务器通信

 

 

Http请求消息

HTTP请求报文由3部分组成(请求行+请求头+请求体)

 

Http响应消息

 HTTP的响应报文也由三部分组成(响应行+响应头+响应体):

 

Http服务器实现

HttpServerCodec是对http消息编码和解码,相当于:HttpRequestDecoder和HttpResponseEncoder。因此在pipline.addLast时要么开始就添加一个HttpServerCodec,或HttpRequestDecoder和HttpResponseEncoder分开添加。

public class HttpServer {
    public static void main(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGoup = new NioEventLoopGroup(8);
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup, workGoup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //  HttpServerCodec 是 netty 提供的处理 http 的 编-解码器
                            pipeline.addLast("httpServerCodec", new HttpServerCodec());
                            // 增加一个自定义的 handler
                            pipeline.addLast("MyHttpServerHandler", new MyHttpServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(7777).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workGoup.shutdownGracefully();
        }
    }
}

    业务处理器

public class MyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest){

            System.out.println("pipeline hashcode" + ctx.pipeline().hashCode() + " myHttpServerHandler hash=" + this.hashCode());
            System.out.println("msg 类型:" + msg.getClass());
            System.out.println("客户端地址:" + ctx.channel().remoteAddress());

            HttpRequest httpRequest = (HttpRequest) msg;
            String uri = httpRequest.uri();
            System.out.println("uri" + uri);
            URI httpUri = new URI(uri);
            // 处理请求
            if ("/list".equals(httpUri.getPath())){
                System.out.println("调用list接口");
                return ;
            }
            if ("/add".equals(httpUri.getPath())){
                System.out.println("调用add接口");
                return ;
            }
            ByteBuf content = Unpooled.copiedBuffer("对不起, 资源没有找到!", CharsetUtil.UTF_8);
            // 构建一个响应
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
            ctx.writeAndFlush(httpResponse);
        }
    }
}

使用浏览器进行访问:

案例

静态服务服务器

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值