前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【netty】实现http服务

【netty】实现http服务

原创
作者头像
无敌小菜鸟
发布2022-05-30 08:43:55
8200
发布2022-05-30 08:43:55
举报
文章被收录于专栏:搬砖笔记

学习netty的小案例,用netty实现一个http服务。

一、需求


  1. Netty 服务器在 8888 端口监听,浏览器发出请求 "http://localhost:8888/ "
  2. 服务器可以回复消息给客户端 "Hello! 我是服务器 " , 并对特定请求资源进行过滤.
  3. 目的:Netty 也可以做Http服务开发,并且理解Handler实例和客户端及其请求的关系

二、服务端代码

HttpNettyServer

代码语言:javascript
复制
public class HttpNettyServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup(1);
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new HttpChannelInitializer());

            ChannelFuture cf = sb.bind(8888).sync();
            cf.addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println("http is ready");
                }
            });
            cf.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}

HttpChannelInitializer

代码语言:javascript
复制
public class HttpChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) {
        // 向管道加入处理器
        // 获取 管道
        ChannelPipeline pipeline = ch.pipeline();
        // 加入netty 提供的 HttpSeverCodec  codec => [coder - decoder]
        // HttpSeverCodec 是 netty 提供的 处理Http 的编-解码器
        pipeline.addLast("MyHttpServerCodec", new HttpServerCodec());
        // 增加一个自定义的 handler
        pipeline.addLast("MyHttpServerHandler", new HttpServerHandler());

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

HttpServerHandler

代码语言:javascript
复制
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    // 读取客户端数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {

        System.out.println("1对应的channel=" + ctx.channel() + ",pipeline=" + ctx
                .pipeline() + " 通过pipeline获取channel" + ctx.pipeline().channel());

        System.out.println("2当前ctx的handler=" + ctx.handler());

        System.out.println("3msg类型:" + msg.getClass());
        System.out.println("4客户端地址:" + ctx.channel().remoteAddress());

        // 回复信息给浏览器[Http 协议]
        if (msg instanceof HttpRequest) {

            System.out.println("5ctx 类型=" + ctx.getClass());
            System.out.println("6pipeline hashcode" + ctx.pipeline().hashCode() + " TestHttpServerHandler hash=" + this.hashCode());

            HttpRequest request = (HttpRequest) msg;
            // 获取Uri,过滤指定的资源
            String uri = request.uri();
            System.out.println(uri);
            if (uri.contains("favicon.ico")) {
                return;
            }


            ByteBuf content = Unpooled.copiedBuffer("Hello,我是服务器", CharsetUtil.UTF_8);
            // 构造一个Http的响应,即httpResponse
            FullHttpResponse httpResponse
                    = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);

            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=utf-8");
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            // 返回
            ctx.writeAndFlush(httpResponse);
        }

    }
}

三、测试

地址:http://localhost:8888/

1
1

控制台

2
2

完!


腾云先锋(TDP,Tencent Cloud Developer Pioneer)是腾讯云GTS官方组建并运营的技术开发者群体。这里有最专业的开发者&客户,能与产品人员亲密接触,专有的问题&需求反馈渠道,有一群志同道合的兄弟姐妹。来加入属于我们开发者的社群吧!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、需求
  • 二、服务端代码
  • 三、测试
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档