netty server端基本使用框架梳理

    public static void main(String[] arg)throws Exception{
        //NioEventLoopGroup 死循环
        //netty的服务器会启动两个服务器,boss来接收连接,worker用来处理连接及响应。
        //本质上都是nio的异步处理的事件循环对象
        EventLoopGroup bossG = new NioEventLoopGroup();
        EventLoopGroup workerG = new NioEventLoopGroup();
        try {
            //启动服务器,ServerBootstrap辅助启动封装类
            //ServerBootstrap里面封装了netty的相关属性和方法,简化netty服务器的创建工作
            ServerBootstrap bootstrap = new ServerBootstrap();
            //方法链形式(返回对象),装配启动类属性
            bootstrap.group(bossG, workerG)
                    .channel(NioServerSocketChannel.class)//netty里对nio的ServerSocketChannel进行了封装
                    .childHandler(new TestServerInitializer());//childHandler针对worker,用来处理交给woeker的连接
            //服务器真正启动,
            //sync(阻塞方法)用来等待和同步连接
            //返回ChannelFuture集成Future,调用异步方法后直接返回Future,里面方法可判断异步操作是否结束
            ChannelFuture channelFuture = bootstrap.bind(8899).sync();
            //netty关闭操作
            channelFuture.channel().closeFuture().sync();
        }finally{
            //netty优雅关闭?
            //如果关闭的时候有连接还没处理,在可控的时间里,把连接处理完,并不接受新的连接
            bossG.shutdownGracefully();
            workerG.shutdownGracefully();
        }
    }
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    public void initChannel(SocketChannel ch) throws Exception{
        //获得channel的管道,可添加编解码器,可用netty提供方法或自定义
        //请求处理类TestServerHandler
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("httpServerCodec",new HttpServerCodec());
        pipeline.addLast("testServerHandler",new TestServerHandler());
    }
}
//SimpleChannelInboundHandler,入栈,数据从外边进来。SimpleChannelOutboundHandler,出栈,把数据发到客户端,
public class TestServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    //ChannelHandlerContext 消息对象,HttpObject 请求对象,真正传入的数据类型
    //连接进来时  handlerAdded-》channelRegistered-》channelActive-》channelRead0-》channelInactive-》channelUnregistered
    @Override
    public void channelRead0(ChannelHandlerContext ctx,HttpObject msg)throws Exception{
        if(msg instanceof HttpRequest){
            out.println("remote address:"+ctx.channel().remoteAddress());
            URI url = new URI(((HttpRequest) msg).uri());
            if(url.getPath().equals("/favicon.ico")){
                   out.println("from brows " );
                   out.println(((HttpRequest) msg).method());
            }
            ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);
            FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1
                    , HttpResponseStatus.OK,content);
            res.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            res.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());

            ctx.writeAndFlush(res);
            ctx.channel().close();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx)throws Exception{
        out.println("channel active");
        super.channelActive(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx)throws Exception{
        out.println("channel registered");
        super.channelRegistered(ctx);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception{
        out.println("handler added");
        super.handlerAdded(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx)throws Exception{
        out.println("channel inactive");
        super.channelInactive(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        out.println("channel unregistered");
        super.channelUnregistered(ctx);
    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肚子饿没人理

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值