Grizzly NIO框架 理论篇 【2】
Transports and Connections
这两个东西,是灰熊框架的核心结构~Transports工具包含有TCP或UDP的协议,合并各种组件资源(Thread-Pool 线程池、Memory Manager 内存管理器等等。

从结构来说,没什么东西,主要还是使用上
1、使用Future模式建立Connection
Future<Connection> clientConnectionFuture = tcpNioTransport.connect("grizzly.java.net",80);Connection clientConnection = clientConnectionFuture.get();
2、可以针对Connection添加CloseHandler等事件处理
Connection conn;conn.addCloseListener(newCloseListener<Closeable,ICloseType>(){@Overridepublicvoid onClosed(Closeable closeable,ICloseType type)throwsIOException{// TODO Auto-generated method stub}});
FilterChains and Filters
过滤器给予了Grizzly无限扩展性。FilterChains是Filter的过程封装,可以对Filter的逐步处理。
比如要扩展成http、Filter组合如下:

比如要给把http修改成https,那么只需要增加SSLFilter:

其中,Transport Filter是所有处理的基础,用于和Grizzly的Selector交互;
另外我认需要认识下BaseFilter,所有Filter都继承于它:
- /**
- * 读流程,读取网络数据,或上一个Filter read之后的message
- */
publicNextAction handleRead(FilterChainContext ctx)throwsIOException;- /**
- * 写流程,写如网络数据,或者处理上一个Filter write之后的message
- */
publicNextAction handleWrite(FilterChainContext ctx)throwsIOException;- /**
- * 新加入的连接
- */
publicNextAction handleConnect(FilterChainContext ctx)throwsIOException;- /**
- * 同handleConnect
- */
publicNextAction handleAccept(FilterChainContext ctx)throwsIOException;- /**
- * 连接断开之后调用
- */
publicNextAction handleClose(FilterChainContext ctx)throwsIOException;
两个Filter之间如何衔接起来,我们需要了解NextAction是怎么工作,并有哪些类型:
StopAction
如果要停止Filter当前工作流程,就直接返回
return ctx.getStopAction();
如果需要中断工作,并把当前没有处理的数据流放到下一次调用,可以加入参数:
return ctx.getStopAction(incompleteChunk);
InvokeAction
如果是继续下一次Filter流程,就返回InvokeAction
return ctx.getInvokeAction();
如果数据流里面有粘包(两个数据包一起发来,我们需要一个个处理),同样可以添加参数:
return ctx.getInvokeAction(incompleteChunk);
RerunFilterAction
return ctx.getRerunFilterAction()
这个就是当前Filter的action多执行一次。
SuspendAction
return ctx.getSuspendAction();
这个是暂停。。。。中断线程,并且通过另外一个线程调用
ctx.resume():
ForkAction (was SuspendStopAction)
return ctx.getForkAction();
和上一个类似。

浙公网安备 33010602011771号