Netty 系列五 Netty重要对象介绍

ServerBootstrap 服务器端的启动配置类,主要作用是将netty的各个组件串联到一起,客户端的配置类Bootstrap 主要的方法有

public ServerBootstrap group(EventLoopGroup group)  装配一个线程组 一般客户端使用这个方法 客户端只需要有一个workgroup来处理事件

public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup)  装配两个线程组 服务器端会有这用这个方法,一个bossgroup 专门负责处理accept链接事件 workergroup 专门用来处理读写事件

public  ServerBootstrap childOption(ChannelOption childOption, T value) 给获取到的serverChannel添加配置public 

ServerBootstrap childHandler(ChannelHandler childHandler) 向workGroup线程组中添加一个handler 

ChannelHandler  handler(ChannelHandler childHandler) 向bossGroup线程组中添加一个handler
Future ChannelFuture 
 

netty中的所有的操作都是异步的,这个两个都是用来异步操作都返回的对象,可以通过这两个对象添加监听来获取最后的操作结果,跟多线程中的Future功能类似 主要方法

ChannelFuture addListener(GenericFutureListener> listener); 添加一个监听
ChannelFuture removeListener(GenericFutureListener> listener);移除一个监听ChannelFuture sync() throws InterruptedException;异步操作
Channel 接口

netty网络通信的重要组件 功能   获取通过远程地址      可以读.写数据    重要的实现类

NioServerSockerChannel  异步的Tcp连接的服务端

NioSocketChannel 异步的TCP连接的客户端

NioDatagramChannel 异步的UDP连接

NioSctpChannel 异步的客户端stcp连接

NioSctpServerChannel 异步的服务器端连接

Channelhandler 

是接口 可以处理IO操作 也可以拦截IO操作并将其转发到ChannelPipeline(业务处理链中) 他的子类提供了丰富的方法

 

Netty 系列五 Netty重要对象介绍_第1张图片

下面是几个重要的方法 自定义的handler可以在下面的方法中实现自己的业务逻辑

//管道注册的事件触发
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
    ctx.fireChannelRegistered();
}
//管道可用的事件时候触发
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ctx.fireChannelActive();
}
//管道可读的事件触发
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ctx.fireChannelRead(msg);
}
//管道读取完成事件触发
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    ctx.fireChannelReadComplete();
}
//发生异常事件的时候触发
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.fireExceptionCaught(cause);
}

Channelpipeline

channelPipeline是一个Handler的集合,他处理各种inbound 和 outbound (出栈 入栈)的事件,

每个Channel有且仅有一个ChannelPipeline与之对应,ChannelPipeline中维护了一个ChannelHandlerContext双向链表结构

链表中的节点存放的就是Handler

// 在链表头部添加一个handler
ChannelPipeline addFirst(String var1, ChannelHandler var2);
// 在链表头部添加一个handler
ChannelPipeline addFirst(EventExecutorGroup var1, String var2, ChannelHandler var3);
// 在链尾添加一个handler
ChannelPipeline addLast(String var1, ChannelHandler var2);

ChannelHandlerContext

保存于channnel相关的上下文的所有的信息

EventLoopGroup

EventLoopGroup是一组eventLoop的抽象,可以理解城一个线程池,里面的线程就是eventLoop,每个eventLoop维护一个Selector实例,eventLoop工作就是不断的循环查看Selector上注册的Channel有没有什么事件发生;

通常服务端会有两个EventLoopGroup 一个是bossLoopGroup专门用来处理Accept连接事件,Accept()得到一个SocketChannel,将这个SocketChannel传递给另外一个workerLoopGroup,workerLoopGroup得到SocketChannel后会将其注册到自己的一个eventLoop中的一个Selector上,通过selector来管理各种channel的事件

 

 

 

你可能感兴趣的:(技术人生)