基于Netty实现HTTP服务器功能

实现效果:

1. Netty服务启动对特定端口如:8081进行监听

2. 在浏览器通过 http://localhost:8081/aaaa 发送请求,Netty服务可以进行相应响应到浏览器

1. 引入netty依赖

<dependency>
	<groupId>io.netty</groupId>
	<artifactId>netty-all</artifactId>
	<version>4.1.42.Final</version>
</dependency>

2. 定义NettyHttpServer类,实现Netty的服务监听

public class NettyHttpServer {
    private int port;

    public NettyHttpServer(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = null; // bossGroup 线程组
        EventLoopGroup workerGroup = null;// workerGroup 线程组

        try {
            bossGroup = new NioEventLoopGroup(1); // bossGroup 线程组
            workerGroup = new NioEventLoopGroup();// workerGroup 线程组
            ServerBootstrap serverBootstrap = new ServerBootstrap(); // 服务端启动助手
            serverBootstrap.group(bossGroup, workerGroup)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {// 创建通道初始化对象
                            // 向 pipeline 添加 HTTPServer编解码器
                            ch.pipeline().addLast(new HttpServerCodec());
                            // http 消息处理 handler
                            ch.pipeline().addLast(new NettyHttpServerHandler());
                        }
                    });
            // 绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(port);
            channelFuture.addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()){
                        System.out.println("端口监听成功~~~~~~~~~~");
                    }else {
                        System.out.println("端口监听失败~~~~~~~~~~");
                    }
                }
            });

            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyHttpServer(8081).run();
    }
}

3. 定义http请求处理类 NettyHttpServerHandler

public class NettyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest){
            DefaultHttpRequest httpRequest = (DefaultHttpRequest) msg;
            String uri = httpRequest.uri(); // 浏览器请求路径
            System.out.println(" 浏览器请求路径 " + uri);

            ByteBuf result = Unpooled.copiedBuffer("我是netty服务器,刚才的请求是 :" + uri, CharsetUtil.UTF_8);
            // 返回信息给浏览器 HttpVersion version, HttpResponseStatus status, ByteBuf content
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, result);
            // 设置必要的头信息
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/html;charset=utf-8");
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, result.readableBytes());
            ctx.writeAndFlush(httpResponse);
        }
    }
}

4. 验证 浏览器输入 http://localhost:8081/aaaa

http://localhost:8081/aa/bb 

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值