一、Netty执行流程和回调机制实战

版权声明:如需转载,请标明转载出处哦! https://blog.csdn.net/Z0157/article/details/82779700

netty的执行流程机制,我们先通过代码案例直接熟悉上手,后面然后拆开分别详细深入剖析,及相关核心代码的源码解析;

我们使用gradle:

compile group: 'io.netty', name: 'netty-all', version: '4.1.29.Final'

package com.zhurong.netty.test1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Description:
 * User: zhurong
 * Date: 2018-09-19  21:20
 */
public class TestServer {

    public static void main(String[] args) throws InterruptedException {
        //接收连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //连接发送给work
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).
                    childHandler(new TestServerInitializer());

            ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }



    }
}

package com.zhurong.netty.test1;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * Description:
 * User: zhurong
 * Date: 2018-09-19  21:29
 */
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("httServerCodec",new HttpServerCodec());
        pipeline.addLast("testHttpServerHandler",new TestHttpServerHandler());
    }
}
package com.zhurong.netty.test1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * Description:
 * User: zhurong
 * Date: 2018-09-19  21:33
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        try{
            if(msg instanceof HttpRequest){
                System.out.println("开始执行成功");
                HttpRequest httpRequest = (HttpRequest) msg;
                System.out.println("请求方法名:"+httpRequest.method().name());
                URI uri = new URI(httpRequest.uri());
                if("/favicon.ico".equals(uri.getPath())){
                    System.out.print("请求ico");
                    return;
                }
                ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);
                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());

                ctx.writeAndFlush(response);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

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

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

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

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

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

猜你喜欢

转载自blog.csdn.net/Z0157/article/details/82779700