尚硅谷2019年Netty教程 http服务器 ----目标netty---step5.20
发布日期:2021-05-04 17:07:42 浏览次数:23 分类:原创文章

本文共 6771 字,大约阅读时间需要 22 分钟。

此示例多次请求 对理解http 是无状态的 协议很有帮助

  • ----- 1: 请求 ; 2: 刷新页面 ; 3:换个浏览器请求 ----
    1. pipeline hashcode : 805440225 ; TestHttpServerHandler : 1092122411
    1. pipeline hashcode : 855020321 ; TestHttpServerHandler : 85665774
    1. pipeline hashcode : 723050666 ; TestHttpServerHandler : 1847229357
      此示例多次请求 对理解http 是无状态的 协议很有帮助

https://www.bilibili.com/video/BV1jK4y1s7GV?p=53 ---- http服务程序实例
https://www.bilibili.com/video/BV1jK4y1s7GV?p=54 ---- http服务程序过滤请求

写一个http服务器(简易版的tomcat)
接受 http://localhost:8097/ 的请求,返回结果给 浏览器

  • 测试步骤
  • step1: 注释 TestHttpServerHandler 中的 如下内容 http://localhost:8097/ ,看效果
    //********************************************************************************
    //获取到http协议头 url ,如果ico 不做响应
    HttpRequest httpRequest= (HttpRequest) msg;
    URI uri = new URI(httpRequest.uri());
    if("/favicon.ico".equals(uri.getPath())){
    System.out.println("请求了 favicon.ico ,不做响应 ");
    return;
    }
    //********************************************************************************
  • 单次请求 浏览器会 向服务器发送两次请求
  • Request URL: http://localhost:8097/
  • Request URL: http://localhost:8097/favicon.ico
  • step2: 取消step1 的注释
  • 同样是请求两次, 针对favicon.ico 的请求没有返回值了
  • step3:
  • 请求后,刷新页面,可以看到 pipeline serverHandler 的hashcode 是不一样的,这个说明http请求是无状态的
  • ----- 1: 请求 ; 2: 刷新页面 ; 3:换个浏览器请求 ----
    1. pipeline hashcode : 805440225 ; TestHttpServerHandler : 1092122411
    1. pipeline hashcode : 855020321 ; TestHttpServerHandler : 85665774
    1. pipeline hashcode : 723050666 ; TestHttpServerHandler : 1847229357
package com.atguigu.http;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioServerSocketChannel;/** * Author: tz_wl * Date: 2020/9/23 13:57 * Content: * * 测试步骤 * step1: 注释  TestHttpServerHandler 中的 如下内容    http://localhost:8097/ ,看效果 //******************************************************************************** //获取到http协议头 url  ,如果ico 不做响应 HttpRequest httpRequest= (HttpRequest) msg; URI uri = new URI(httpRequest.uri()); if("/favicon.ico".equals(uri.getPath())){ System.out.println("请求了 favicon.ico ,不做响应 "); return; } //******************************************************************************** *   单次请求  浏览器会 向服务器发送两次请求 *   Request URL: http://localhost:8097/ *   Request URL: http://localhost:8097/favicon.ico * * step2:  取消step1 的注释 *  同样是请求两次, 针对favicon.ico 的请求没有返回值了 * *  step3: *  请求后,刷新页面,可以看到 pipeline  serverHandler 的hashcode 是不一样的,这个说明http请求是无状态的 * ----- 1: 请求 ; 2: 刷新页面 ; 3:换个浏览器请求  ---- * 1. pipeline hashcode : 805440225 ; TestHttpServerHandler : 1092122411 * 2. pipeline hashcode : 855020321 ; TestHttpServerHandler : 85665774 * 3. pipeline hashcode : 723050666 ; TestHttpServerHandler : 1847229357 * */public class TestServer {       public static void main(String[] args) {           NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);        NioEventLoopGroup workerGroup = new NioEventLoopGroup();        try {               ServerBootstrap serverBootstrap = new ServerBootstrap();            serverBootstrap.group(bossGroup,workerGroup)                    .channel(NioServerSocketChannel.class)                    .childHandler(new TestServerInitializer());   //向服务器增加  Channel            ChannelFuture future = serverBootstrap.bind(8097).sync();            future.channel().closeFuture().sync();        } catch (Exception e) {               e.printStackTrace();        } finally {               bossGroup.shutdownGracefully();            workerGroup.shutdownGracefully();        }    }}
package com.atguigu.http;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.socket.SocketChannel;import io.netty.handler.codec.http.HttpServerCodec;/** * Author: tz_wl * Date: 2020/9/23 14:01 * Content: */public class TestServerInitializer extends ChannelInitializer<SocketChannel> {       @Override    protected void initChannel(SocketChannel ch) throws Exception {           //向管道加入处理器        //得到管道        ChannelPipeline pipeline = ch.pipeline();        //加入 netty提供的  httpServerCodec =  coder + decoder        pipeline.addLast("myHttpServerCodec",new HttpServerCodec());        // 增加自定义的handler        pipeline.addLast("myHttpServerHandler",new TestHttpServerHandler());  // 向pipeline(channel) 增加 handler    }}
package com.atguigu.http;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.DefaultFullHttpResponse;import io.netty.handler.codec.http.DefaultHttpResponse;import io.netty.handler.codec.http.FullHttpResponse;import io.netty.handler.codec.http.HttpHeaderNames;import io.netty.handler.codec.http.HttpObject;import io.netty.handler.codec.http.HttpRequest;import io.netty.handler.codec.http.HttpResponseStatus;import io.netty.handler.codec.http.HttpVersion;import io.netty.util.CharsetUtil;import java.net.URI;import java.nio.ByteBuffer;/** * Author: tz_wl * Date: 2020/9/23 14:06 * Content: * * SimpleChannelInboundHandler :  ChannelInboundHandlerAdapter * HttpObject  客户端服务器  通讯的数据被封装为 httpObject * */public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {       //读取客户端数据    @Override    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {           //判断msg 是否为 httpRequest        if(msg instanceof HttpRequest){               System.out.println(" msg 类型 = "+msg.getClass());  //msg 类型 = class io.netty.handler.codec.http.DefaultHttpRequest            System.out.println(" 客户端地址 "+ ctx.channel().remoteAddress());            System.out.println(" pipeline hashcode : "+ ctx.channel().pipeline().hashCode() + " ; TestHttpServerHandler : "+ this.hashCode() );            //********************************************************************************            //获取到http协议头 url  ,如果ico 不做响应            HttpRequest httpRequest= (HttpRequest) msg;            URI uri = new URI(httpRequest.uri());            if("/favicon.ico".equals(uri.getPath())){                   System.out.println("请求了 favicon.ico ,不做响应 ");                return;            }            //********************************************************************************            String str = "hello expolor , this is server";            //回复信息给浏览器            ByteBuf content = Unpooled.copiedBuffer(str, CharsetUtil.UTF_8);   // String -> ByteBuf            //构造一个 http响应  httpResponse            FullHttpResponse 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);        }    }}
上一篇:尚硅谷2019年Netty教程 netty 群聊系统 ----目标netty---step5.10
下一篇:尚硅谷2019年Netty教程图解从bio到netty演变过程 ----目标netty---step1.01

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月02日 06时56分32秒