龙空技术网

netty教程14-实现http协议测试

南京彭于雁 41

前言:

此时姐妹们对“netty 教程”可能比较着重,我们都想要剖析一些“netty 教程”的相关内容。那么小编在网上收集了一些对于“netty 教程””的相关内容,希望各位老铁们能喜欢,我们快快来学习一下吧!

netty可以实现http,HttpServerCodec类实现了http消息的编解码

看代码:

package com.study.nio.ph2.e6;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.ChannelInboundHandlerAdapter;import io.netty.channel.ChannelInitializer;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.HttpServerCodec;import io.netty.handler.logging.LogLevel;import io.netty.handler.logging.LoggingHandler;import lombok.extern.slf4j.Slf4j;/** * @program: isc-study * * @description: * * @author: wangjinwei * * @create: 2021-11-03 14:26 **/@Slf4jpublic class TestHttp {    public static void main(String[] args) {        NioEventLoopGroup boss = new NioEventLoopGroup();        NioEventLoopGroup work = new NioEventLoopGroup();        try {            ServerBootstrap serverBootstrap = new ServerBootstrap();            serverBootstrap.channel(NioServerSocketChannel.class);            serverBootstrap.group(boss, work);            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {                @Override                protected void initChannel(SocketChannel ch) throws Exception {                    ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));                    ch.pipeline().addLast(new HttpServerCodec());                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {                        @Override                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {                            log.info("msg class ={}", msg.getClass());                        }                    });                }            });            ChannelFuture future = serverBootstrap.bind(8080).sync();            future.channel().closeFuture().sync();        } catch (Exception e) {            e.printStackTrace();        } finally {            boss.shutdownGracefully();            work.shutdownGracefully();        }    }}

在浏览器里输入,如下图所示:

服务端输出结果:

结果里msg class ={}打印了2次 DefaultHttpRequest和LastHttpContent$1

一个是,请求行请求头,还有一个是 请求体

修改代码,用SimpleChannelInboundHandler,我只关心DefaultHttpRequest的消息:

package com.study.nio.ph2.e6;import io.netty.bootstrap.ServerBootstrap;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.DefaultFullHttpResponse;import io.netty.handler.codec.http.HttpRequest;import io.netty.handler.codec.http.HttpResponseStatus;import io.netty.handler.codec.http.HttpServerCodec;import io.netty.handler.logging.LogLevel;import io.netty.handler.logging.LoggingHandler;import lombok.extern.slf4j.Slf4j;import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;/** * @program: isc-study * * @description: * * @author: wangjinwei * * @create: 2021-11-03 14:26 **/@Slf4jpublic class TestHttp {    public static void main(String[] args) {        NioEventLoopGroup boss = new NioEventLoopGroup();        NioEventLoopGroup work = new NioEventLoopGroup();        try {            ServerBootstrap serverBootstrap = new ServerBootstrap();            serverBootstrap.channel(NioServerSocketChannel.class);            serverBootstrap.group(boss, work);            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {                @Override                protected void initChannel(SocketChannel ch) throws Exception {                    ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));                    ch.pipeline().addLast(new HttpServerCodec());                    ch.pipeline().addLast(new SimpleChannelInboundHandler<HttpRequest>() {                        @Override                        protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {                            //获取请求头                            log.info(msg.uri());                            //返回客户端请求内容                            DefaultFullHttpResponse response = new DefaultFullHttpResponse(msg.protocolVersion(), HttpResponseStatus.OK);                            byte[] bytes = "<h1>Hello, world!</h1>".getBytes();                            //告诉客户端返回内容的长度                            response.headers().setInt(CONTENT_LENGTH,bytes.length);                            response.content().writeBytes(bytes);                            ctx.writeAndFlush(response);                        }                    });/*                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {                        @Override                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {                            log.info("msg class ={}", msg.getClass());                        }                    });*/                }            });            ChannelFuture future = serverBootstrap.bind(8080).sync();            future.channel().closeFuture().sync();        } catch (Exception e) {            e.printStackTrace();        } finally {            boss.shutdownGracefully();            work.shutdownGracefully();        }    }}

运行结果

标签: #netty 教程