基于Netty的http服务器

85 篇文章 1 订阅
44 篇文章 0 订阅

Server

public class Server {
    public static void main(String[] args) throws InterruptedException {
        //创建两个事件循环组,bossGroup只处理连接请求,workGroup处理客户端业务处理,交给bossGroup
        //两个都是无线循环
        //默认CPU核*2
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            //创建服务端启动对象,配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();

            //用链式编程进行设置
            bootstrap.group(bossGroup, workGroup)//设置两个线程组
                    .channel(NioServerSocketChannel.class)//使用NioSocketChannel作为服务器通道实现
                    .option(ChannelOption.SO_BACKLOG, 128)//设置线程队列个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)//设置保持活动连接状态
                    .childHandler(new ServerInitializer());//给workGroup的EventLoop对应的管道设置处理器

            System.out.println(LocalDateTime.now() + "服务器准备好了");

            //启动服务器,绑定端口,生成ChannelFuture对象
            ChannelFuture future = bootstrap.bind(888).sync();

            //给ChannelFuture注册监听器,监控关心的事件
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(future.isSuccess()){
                        System.out.println("监听端口成功");
                    }else {
                        System.out.println("监听端口失败");
                    }
                }
            });

            //对关闭通道进行监听(非阻塞监听,异步模型)
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}

ServerHandler

// 客户端与服务端相互通讯数据封装成HttpObject
public class ServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        //判断msg是不是HttpRequest请求
        if (msg instanceof HttpRequest) {
            System.out.println("pipeline hashcode :" + ctx.pipeline().hashCode());
            System.out.println("ServerHandler hashcode :" + this.hashCode());
            System.out.println("msg类型为:" + msg.getClass());
            System.out.println("客户端地址:" + ctx.channel().remoteAddress());
            //获取request
            HttpRequest request = (HttpRequest) msg;
            //获取uri
            URI uri = new URI(request.uri());
            if("/favicon.ico".equals(uri.getPath())){
                //System.out.println("请求了favicon.ico不做相应");
                return;
            }
            //回复浏览器
            ByteBuf buf = Unpooled.copiedBuffer("我是netty服务器", CharsetUtil.UTF_8);
            //构造http相应
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html;charset=utf-8")
                    .set(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());

            ctx.writeAndFlush(response);
        }
    }

    //处理异常,关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

ServerInitializer

public class ServerInitializer extends ChannelInitializer<SocketChannel> {
    //给pipeline设置处理器
    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        //向管道添加httpServerCodec
        channel.pipeline().addLast("HttpServerCodec",new HttpServerCodec())//一个参数为自定义名
        .addLast("ServerHandler",new ServerHandler());//添加自定义Handler
    }
}

结果

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值