展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

HTTP服务案例

  • 之前的案例如下

  • 现在将ChannelInitializer提取出来

  • 编写服务端

public class TestServer {
    public static void main(String[] args) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(
                    new com.ychen.netty.netty.http.TestServerInitializer());

            ChannelFuture channelFuture = serverBootstrap.bind(8889).sync();
            
            channelFuture.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
  • 编写初始化方法
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {

        //向管道加入处理器
        //得到管道
        ChannelPipeline pipeline = ch.pipeline();
        //加入一个netty 提供的httpServerCodec codec =>[coder - decoder]
        //HttpServerCodec 说明
        //1. HttpServerCodec 是netty 提供的处理http的 编-解码器
        pipeline.addLast("MyHttpServerCodec",new HttpServerCodec());
        //2. 增加一个自定义的handler
        pipeline.addLast("MyTestHttpServerHandler", new com.ychen.netty.netty.http.TestHttpServerHandler());

        System.out.println("ok~~~~");

    }
}
  • 编写处理器
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    //channelRead0 读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        //判断 msg 是不是 httprequest请求
        if(msg instanceof HttpRequest) {
            System.out.println("msg 类型=" + msg.getClass());
            System.out.println("客户端地址" + ctx.channel().remoteAddress());

            //回复信息给浏览器 [http协议]
            ByteBuf content = Unpooled.copiedBuffer("hello, 我是服务器", CharsetUtil.UTF_8);

            //构造一个http的相应,即 httpresponse
            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());

            //将构建好 response返回
            ctx.writeAndFlush(response);
        }
    }

}
  • 启动服务端测试
# 浏览器访问
http://localhost:8889/

# 控制台打印如下
ok~~~~
msg 类型=class io.netty.handler.codec.http.DefaultHttpRequest
客户端地址/0:0:0:0:0:0:0:1:60532
msg 类型=class io.netty.handler.codec.http.DefaultHttpRequest
客户端地址/0:0:0:0:0:0:0:1:60532

# 之所以会打印2次

  • 过滤图标
# 处理器中添加如下
HttpRequest httpRequest = (HttpRequest) msg;
//获取uri, 过滤指定的资源
URI uri = new URI(httpRequest.uri());
if("/favicon.ico".equals(uri.getPath())) {
    System.out.println("请求了 favicon.ico, 不做响应");
    return;
}
posted @ 2022-08-08 17:23  DogLeftover  阅读(17)  评论(0编辑  收藏  举报