Netty guide the interpretation process

Channel lifecycle status will change to [state transition corresponding event, forwarded for processing to ChannelPipeline in ChannelHandler]
  ChannelUnregistered: Channel has been created, but not yet registered to EventLoop
  ChannelRegistered: Channel already been registered to EventLoop
  ChannelActive: Channel is active state (it is connected to a remote node). It can now receive and send data
  ChannelInactive: Channel is not connected to the remote node


[ChannelHandler lifecycle added or removed when ChannelPipeline call these methods, it has two subclasses ChannelInboundHandler ChannelOutboundHandler]
  handlerAdded: When added to ChannelHandler ChannelPipeline when invoked
  handlerRemoved: Upon removal from the ChannelHandler ChannelPipeline are invoked
  exceptionCaught: when when the process is called an error occurred in the ChannelPipeline


ChannelInboundHandler Interface [inbound]
  channelRegistered: When Channel has been registered to its EventLoop and can handle I / O is called
  channelUnregistered: When the Channel from its EventLoop logout and can not process any I / O is called
  channelActive: When Channel is active state is called; Channel connection has / have been bound and ready
  channelInactive: Channel when leaving the active state and it is no longer connected to the remote node is invoked
  channelReadComplete: when a read operation is completed is called the Channel
  channelRead: when the Channel It is called when the data read by SimpleChannelInboundHandler channelRead0 [method]
  ChannelWritability changed: Channel is called when the writable state changes. Users can ensure that the write operation will not be completed too quickly (to avoid OutOfMemoryError) or can become resume written in Channel writable again. Writability may be detected by isWritable Channel () method is called the Channel. . Writable related threshold can Channel.config () setWriteHighWaterMark () and Channel.config () setWriteLowWater- Mark () method to set
  userEventTriggered: when ChannelnboundHandler.fireUserEventTriggered () method is called is called, because a POJO is passed through the ChannelPipeline


ChannelOutboundHandler Interface [outbound demand to postpone the operation or event (download file is paused)] Channel-> ChannelPipeline-> ChannelOutboundHandler
  the bind (ChannelHandlerContext, SocketAddress, ChannelPromise): When a request to a local address to bind Channel is called
  connect (ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise): when a request to connect to the remote node is invoked Channel
  disconnect (ChannelHandlerContext, ChannelPromise): when a Channel disconnect request from the remote node is invoked
  close (ChannelHandlerContext, ChannelPromise): when the request is closed Channel call
  deregister (ChannelHandlerContext, ChannelPromise): when a Channel request when it is called from the logout EventLoop
  read (ChannelHandlerContext): when a request to read more data from Channel is called
  flush (ChannelHandlerContext): when requested by the enqueue Channel It is called when the data is flushed to the remote node
  write (ChannelHandlerContext, Object, ChannelPromise) : when Channel request by writing data to the remote node is invoked

Resource Leak: Netty provides a class ResourceLeakDetector [java -Dio.netty.leakDetectionLevel = ADVANCED]

ChannelPipeline Interface [Each Channel newly created will be assigned a new ChannelPipeline]
ChannelPipeline saved ChannelHandler associated with Channel;
ChannelPipeline can If necessary, dynamically modified by adding or deleting ChannelHandler;
the ChannelPipeline rich API to be called in response to inbound and outbound events
ChannelHanlderContext [each added a Handler, will bind a new ChannelHanlderContext]
by calling pipeline on ChannelHandlerContext () method to obtain a reference of the enclosed ChannelPipeline. This enables to operate ChannelHandler ChannelPipeline runtime, we can use this to achieve some complex designs. For example, you can dynamically switching protocol ChannelHandler by adding to the ChannelPipeline.
Exception handling
default ChannelHandler.exceptionCaught () implementation is simply forwards the current exception to ChannelPipeline the next ChannelHandler;
if abnormal reached the end of ChannelPipeline, it will be recorded as unprocessed;
To define custom processing logic, you need to override exceptionCaught () method. Then you need to decide whether the abnormal spread out.

Each Thread EventLoop by a support 
EventLoopGroup bossGroup = new NioEventLoopGroup (); // default value is created Thread Math.max (1, SystemPropertyUtil.getInt ( "io.netty.eventLoopThreads ", NettyRuntime.availableProcessors () * 2) );

  

EventLoopGroup oiobossGroup = new OioEventLoopGroup();

  

AbstractBootstrap <AbstractBootstrap the extends B <B, C>, the extends Channel C>
B the extends AbstractBootstarp <B, C> subtype is a supertype of parameter type, the instance may return a reference to the runtime mode support call chain with the Bootstrap ServerBootstrap method

  Bootstrap group(EventLoopGroup):设置用于处理Channel所有事件的EventLoopGroup
  Bootstrap channel(Class<? extends C>)Bootstrap channelFactory(ChannelFactory<? extends C>):channel()方法指定了Channel的实现类。如果该实现类没提供默认的构造函数[7],可以通过调用channel- Factory()方法来指定一个工厂类,它将会被bind()方法调用
<T> Bootstrap option(ChannelOption<T> option,T value):设置ChannelOption,其将被应用到每个新创建的Channel的ChannelConfig。这些选项将会通过bind()或者connect()方法设置到Channel,不管哪个先被调用。这个方法在Channel已经被创建后再调用将不会有任何的效果。支持的ChannelOption取决于使用的Channel类型。
<T> Bootstrap attr(Attribute<T> key, T value):指定新创建的Channel的属性值。这些属性值是通过bind()或者connect()方法设置到Channel的,具体取决于谁最先被调用。这个方法在Channel被创建后将不会有任何的效果。
  Bootstrap handler(ChannelHandler):设置将被添加到ChannelPipeline以接收事件通知的ChannelHandler
  Bootstrap clone():创建一个当前Bootstrap的克隆,其具有和原始的Bootstrap相同的设置信息
  Bootstrap remoteAddress(SocketAddress):设置远程地址。或者,也可以通过connect()方法来指定它
  ChannelFuture connect():连接到远程节点并返回一个ChannelFuture,其将会在连接操作完成后接收到通知
  ChannelFuture bind():绑定Channel并返回一个ChannelFuture,其将会在绑定操作完成后接收到通知,在那之后必须调用Channel. connect()方法来建立连接

 

EventLoopGroup bossGroup = new NioEventLoopGroup();//处理channel所有事件的group
ServerBootstrap serverBootstrap = new ServerBootstrap();//创建和连接新的服务端channel
serverBootstrap.group(bossGroup, workerGroup)//提供处理新链接channel事件的事件组
      .channel(NioServerSocketChannel.class)//指定所用的channel
      .childHandler(new ChannelInitializer<SocketChannel>() {//设置处理channel事件和数据的handler
         @Override
         public void initChannel(SocketChannel ch) throws Exception {

  

ServerBootstrap bootstrap = new ServerBootstrap();  // ← --  创建ServerBootstrap 以创建ServerSocketChannel,并绑定它
bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup())// ← --  设置EventLoopGroup,其将提供用以处理Channel 事件的EventLoop
        .channel(NioServerSocketChannel.class)// ← --  指定要使用的Channel 实现
        .childHandler(// ← --  设置用于处理已被接受的子Channel 的I/O 和数据的ChannelInboundHandler
                new SimpleChannelInboundHandler<ByteBuf>() {
                    ChannelFuture connectFuture;
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        Bootstrap bootstrap = new Bootstrap();// ← --  创建一个Bootstrap类的实例以连接到远程主机
                        bootstrap.channel(NioSocketChannel.class).handler(//  ← --  指定Channel的实现
                                new SimpleChannelInboundHandler<ByteBuf>() {  // ← -- 为入站I/O 设置ChannelInboundHandler
                                    @Override
                                    protected void channelRead0(
                                            ChannelHandlerContext ctx, ByteBuf in)
                                            throws Exception {
                                        System.out.println("Received data");
                                    }
                                });
                        bootstrap.group(ctx.channel().eventLoop());// ← --  使用与分配给已被接受的子Channel 相同的EventLoop
                        connectFuture = bootstrap.connect(
                                new InetSocketAddress("www.123.com", 80)); //  ← --  连接到远程节点
                    }

                    @Override
                    protected void channelRead0(
                            ChannelHandlerContext channelHandlerContext,
                            ByteBuf byteBuf) throws Exception {
                        if (connectFuture.isDone()) {//当连接完成时,执行一些数据操作(如代理)
                        }
                    }
                });
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080));// ← --  通过配置好的ServerBootstrap绑定该Server-SocketChannel
future.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture channelFuture)
            throws Exception {
        if (channelFuture.isSuccess()) {
            System.out.println("Server bound");
        } else {
            System.err.println("Bind attempt failed");
            channelFuture.cause().printStackTrace();
        }
    }
});

  

 

Guess you like

Origin www.cnblogs.com/htkj/p/10932637.html