我们上一篇提到了talent-aio的四类Task:DecodeRunnableHandlerRunnableSendRunnableCloseRunnable,并且分析了这些task的基类AbstractQueueRunnable。在这篇文章中,我们就来分析一下这几个task是如何相互协作来处理输入、输出数据以及客户端连接的。

talent-aio 基础类介绍


在开始介绍前,我们需要先介绍几个talent-aio的基础类和接口,在处理输入输出的整个流程中,都需要用到它们。两个基础的类为:

ChannelContext
GroupContext

其中ChannelContext类包含:

  1. AsynchronousSocketChannel对象、与该连接有关的
  2. DecodeRunnableHandlerRunnableSendRunnableCloseRunnable
  3. GroupContext
  4. ReadCompletionHandler
    ChannelContext类代表一个socket连接,封装了:连接对应的AsynchronousSocketChannel对象;解码、处理接收到的数据和发送数据、关闭连接的几个Runnable;该连接所属的GroupContext引用;该连接的ReadCompletionHandler等。

在创建ChannelContext的过程中,首先记录accept返回的asynchronousSocketChannel:

     public void setAsynchronousSocketChannel(AsynchronousSocketChannel
asynchronousSocketChannel)
{
this.asynchronousSocketChannel = asynchronousSocketChannel; if (asynchronousSocketChannel != null)
{
try
{
clientNode = getClientNode(asynchronousSocketChannel);
} catch (IOException e)
{
log.error(e.toString(), e);
}
} else
{
clientNode = null;
}
}

而后设置GroupContext,并创建几个Runnable,最终将自己加入GroupContext管理的连接集合connections和对端集合clientNodes中:

    public void setGroupContext(GroupContext<Ext, P, R> groupContext)
{
this.groupContext = groupContext; if (groupContext != null)
{
decodeRunnable = new DecodeRunnable<>(this,
groupContext.getDecodeExecutor());
closeRunnable = new CloseRunnable<>(this, null,
null, groupContext.getCloseExecutor()); handlerRunnableNormPrior = new HandlerRunnable<>(this,
groupContext.getHandlerExecutorNormPrior()); sendRunnableNormPrior = new SendRunnable<>(this,
groupContext.getSendExecutorNormPrior()); groupContext.getConnections().add(this);
groupContext.getClientNodes().put(this);
}
}

而GroupContext管理着当前实例的所有连接connections、连接对应的用户users以及用户间的分组关系groups:

    protected ClientNodes<Ext, P, R> clientNodes = new ClientNodes<>();
protected Connections<Ext, P, R> connections = new Connections<>();
protected Groups<Ext, P, R> groups = new Groups<>();
protected Users<Ext, P, R> users = new Users<>();

除此之外,GroupContext还管理着一些线程池:

/**
* 解码线程池
*/
private SynThreadPoolExecutor<SynRunnableIntf> decodeExecutor; /**
* 关闭连接的线程池
*/
private SynThreadPoolExecutor<SynRunnableIntf> closeExecutor; /**
* 业务处理线程池
*/
private SynThreadPoolExecutor<SynRunnableIntf> handlerExecutorNormPrior; /**
* 消息发送线程池
*/
private SynThreadPoolExecutor<SynRunnableIntf> sendExecutorNormPrior;

在处理输入输出的过程中我们会用到上面这两个类。

talent-aio的主要的业务逻辑都在AioHandler接口的实现类中,AioHandler接口为:

public interface AioHandler<Ext, P extends Packet, R>
{ /**
* 处理消息包
*
* @param packet the packet
* @return the r
* @author: tanyaowu
* @创建时间: 2016年11月15日 上午11:38:52
*/
R handler(P packet,
ChannelContext<Ext, P, R> channelContext) throws Exception; /**
* 编码
*
* @param packet the packet
* @return the byte buffer
* @author: tanyaowu
* @创建时间: 2016年11月15日 上午11:38:52
*/
ByteBuffer encode(P packet,
ChannelContext<Ext, P, R> channelContext); /**
* 根据ByteBuffer解码成业务需要的Packet对象.
*
* @param buffer the buffer
* @return the t
* @throws AioDecodeException the aio decode exception
*/
P decode(ByteBuffer buffer, ChannelContext<Ext, P, R> channelContext)
throws AioDecodeException; }

三个方法分别用来数据解包、数据封包以及处理数据包。

处理流程


读取数据

首先,是处理读取数据:

    public void completed(Integer result, ByteBuffer byteBuffer)
{
GroupContext<Ext, P, R> groupContext
= channelContext.getGroupContext();
if (result > 0)
{
byteBuffer.limit(byteBuffer.position());
byteBuffer.position(0);
DecodeRunnable<Ext, P, R> decodeRunnable
= channelContext.getDecodeRunnable();
decodeRunnable.addMsg(byteBuffer); groupContext.getDecodeExecutor().execute(decodeRunnable); } else if (result == 0)
{
log.error("读到的数据长度为0");
} else if (result < 0)
{
Aio.close(channelContext, null, "读数据时返回" + result);
} if (AioUtils.checkBeforeIO(channelContext))
{
AsynchronousSocketChannel asynchronousSocketChannel
= channelContext.getAsynchronousSocketChannel();
ByteBuffer newByteBuffer =
ByteBuffer.allocate(
channelContext.getGroupContext().getReadBufferSize()
);
asynchronousSocketChannel.read(newByteBuffer,
newByteBuffer, this);
} }

在读取数据后,将byteBuffer提交到decodeRunnable的数据队列中,而后继续调用read方法读取对端发送来的数据。

数据组包

在decodeRunnable中,调用AioHandler的decode方法来获取数据包,然后提交给HandlerRunnable处理。在处理数据时主要考虑了半包和粘包的情况:

@Override
public void runTask()
{
ConcurrentLinkedQueue<ByteBuffer> queue
= getMsgQueue(); ByteBuffer byteBuffer = null;
label_1: while ((size = queue.size()) > 0)
{
byteBuffer = queue.poll();
if (byteBuffer != null)
{
if (lastByteBuffer != null)
{
byteBuffer.position(0);
byteBuffer =
ByteBufferUtils.composite(lastByteBuffer, byteBuffer);
lastByteBuffer = null;
}
} else {
break label_1;
} try
{
byteBuffer.position(0);
label_2: while (true)
{
int initPosition = byteBuffer.position();
P packet =
channelContext.
getGroupContext().
getAioHandler().
decode(byteBuffer, channelContext); if (packet == null)// 数据不够,组不了包
{
if (log.isDebugEnabled())
{
log.debug("{},数据不够,组不了包",
channelContext.toString());
}
byteBuffer.position(initPosition);
lastByteBuffer = byteBuffer;
continue label_1;
} else //组包成功
{
channelContext.getStat().
setLatestTimeOfReceivedPacket(
SystemTimer.currentTimeMillis()
);
int afterDecodePosition = byteBuffer.position();
int len = afterDecodePosition - initPosition;
AioListener<Ext, P, R> aioListener
= channelContext.getGroupContext().getAioListener();
if (aioListener != null)
{
aioListener.
onAfterDecoded(channelContext, packet, len);
}
submit(packet, len);
channelContext.getGroupContext().
getGroupStat().
getReceivedPacket().
incrementAndGet(); channelContext.getGroupContext().
getGroupStat().
getReceivedBytes().
addAndGet(len); if (byteBuffer.hasRemaining())//组包后,还剩有数据
{
if (log.isDebugEnabled())
{
log.debug("{}组包后,还剩有数据:{}",
channelContext, byteBuffer.limit() - byteBuffer.position());
}
continue label_2;
} else//组包后,数据刚好用完
{
lastByteBuffer = null;
log.debug("{},组包后,数据刚好用完",
channelContext);
continue label_1;
}
}
}
} catch (AioDecodeException e)
{
log.error(channelContext.toString(), e);
Aio.close(channelContext, e, "解码异常:"
+ e.getMessage());
break label_1;
} finally
{ }
}
}

在这个循环中,首先从队列中获取数据,获取到数据后,看看是否存在粘包多出来的数据lastByteBuffer, 如果存在则将两部分数据合并。而后调用AioHandler的decode方法处理数据,如果由于半包导致解包失败,则继续从队列中获取数据,组合起来尝试解包;如果解包成功,则将多余的数据放在lastByteBuffer,并且更新各种统计信息。最后,将组好的数据包通过submit方法传递给HandlerRunnable处理。

数据处理

HandlerRunnable的逻辑相对比较简单,从数据队列中获取组好的包,并调用doPacket处理数据包:

    @Override
public void runTask()
{
ConcurrentLinkedQueue<P> queue = getMsgQueue();
P packet = null;
while ((packet = queue.poll()) != null)
{
doPacket(packet);
}
}

在doPacket中,调用AioHandler的hanlder解除处理数据包:

groupContext.getAioHandler().handler(packet, channelContext);

发送数据

发送数据使用Aio类的静态方法send将packet添加到SendRunnable的数据队列中,而后将sendRunnable提交到线程池中运行:

public static <Ext, P extends Packet, R> void send(
ChannelContext<Ext, P, R> channelContext,
P packet
)
{
if (channelContext == null)
{
log.error("channelContext == null");
return;
}
SendRunnable<Ext, P, R> sendRunnable
= AioUtils.selectSendRunnable(channelContext, packet);
sendRunnable.addMsg(packet);
SynThreadPoolExecutor<SynRunnableIntf> synThreadPoolExecutor
= AioUtils.selectSendExecutor(channelContext, packet);
synThreadPoolExecutor.execute(sendRunnable);
}

在线程池中,会尝试一次发送所有等待发送的packet,不过对单次发送的packet设置了一个上限,而后对每个packet编码,汇总到一个ByteBuffer中:

for ( int i = 0; i < queueSize; i++ )
{
if ( (packet = queue.poll() ) != null )
{
ByteBuffer byteBuffer = aioHandler.encode( packet, channelContext );
allBytebufferCapacity += byteBuffer.limit();
packetCount++;
byteBuffers[i] = byteBuffer; if ( aioListener != null )
{
try
{
aioListener.onBeforeSent( channelContext, packet );
} catch ( Exception e )
{
log.error( e.toString(), e );
}
}
} else{
break;
}
}
ByteBuffer allByteBuffer = ByteBuffer.allocate( allBytebufferCapacity );
for ( ByteBuffer byteBuffer : byteBuffers )
{
if ( byteBuffer != null )
{
byteBuffer.flip();
allByteBuffer.put( byteBuffer );
}
}

最终在sendRunnable的sendByteBuffer中完成数据发送,注意发送前需要获取一个信号量,保证同一时间对一个连接只有一个线程在调用发送动作,并在writeCompleteHandler中记录当前连接发送数据,并更新当前连接活动时间,为keepalive做准备:

public void sendByteBuffer( ByteBuffer byteBuffer, Integer packetCount ) {
if ( byteBuffer == null )
{
log.error( "byteBuffer is null" );
return;
} if ( !AioUtils.checkBeforeIO( channelContext ) )
{
return;
} byteBuffer.flip();
AsynchronousSocketChannel asynchronousSocketChannel
= channelContext.getAsynchronousSocketChannel();
WriteCompletionHandler<Ext, P, R> writeCompletionHandler
= channelContext.getWriteCompletionHandler();
try
{
writeCompletionHandler.getWriteSemaphore().acquire();
} catch ( InterruptedException e )
{
log.error( e.toString(), e );
}
asynchronousSocketChannel.write( byteBuffer, packetCount, writeCompletionHandler );
}

注意发送时如果队列中有待发送数据将直接在当前进程中继续运行runTask,而不是重新提交Runnable到线程池中,以尽快发送数据:

if (queue.size() > 0) {
runTask();
}

关闭连接

在关闭连接时,首先将解码,处理,发送runnable全部停止,然后清空其数据队列,最后检查该连接是否已经 调用过关闭,如果没有,就将CloseRunnable提交到线程池中执行:

public static < Ext, P extends Packet, R > void close( ChannelContext<Ext, P, R> channelContext, Throwable t, String remark, boolean isRemove )
{
channelContext.getDecodeRunnable().clearMsgQueue();
channelContext.getHandlerRunnableNormPrior().clearMsgQueue();
channelContext.getSendRunnableNormPrior().clearMsgQueue(); channelContext.getDecodeRunnable().setCanceled( true );
channelContext.getHandlerRunnableNormPrior().setCanceled( true );
channelContext.getSendRunnableNormPrior().setCanceled( true ); CloseRunnable<Ext, P, R> closeRunnable = channelContext.getCloseRunnable();
if ( closeRunnable.isWaitingExecute() )
{
log.error( "{},已经在等待关闭\r\n本次关闭备注:{}\r\n第一次的备注:{}\r\n本次关闭异常:{}\r\n第一次时异常:{}", channelContext, remark, closeRunnable.getRemark(), t, closeRunnable.getT() );
return;
}
synchronized (closeRunnable) {
if ( closeRunnable.isWaitingExecute() ) /* double check */
{
return;
}
closeRunnable.setRemove( isRemove );
closeRunnable.setRemark( remark );
closeRunnable.setT( t );
closeRunnable.getExecutor().execute( closeRunnable );
closeRunnable.setWaitingExecute( true );
}
}

在CloseRunnable的runTask中,主要执行关闭连接,清理连接数据的逻辑:

//关闭连接
try
{
AsynchronousSocketChannel asynchronousSocketChannel = channelContext.getAsynchronousSocketChannel();
if ( asynchronousSocketChannel != null )
{
asynchronousSocketChannel.close();
}
} catch ( Throwable e )
{
log.error( e.toString() );
} //清理连接数据
//删除集合中的维护信息 start
/*删除集合中的维护信息 start */
try
{
groupContext.getConnections().remove( channelContext );
} catch ( Throwable e )
{
log.error( e.toString(), e );
} try
{
groupContext.getClientNodes().remove( channelContext );
} catch ( Throwable e )
{
log.error( e.toString(), e );
} try
{
groupContext.getUsers().unbind( channelContext );
} catch ( Throwable e )
{
log.error( e.toString(), e );
} try
{
groupContext.getGroups().unbind( channelContext );
} catch ( Throwable e )
{
log.error( e.toString(), e );
} channelContext.setClosed( true );
channelContext.getGroupContext().getGroupStat().getClosed().incrementAndGet();
/*删除集合中的维护信息 end */

除此以外,如果连接是因为出错被关闭的,还会根据ReconnConf的配置进行断线重连操作,这个我们将在后文中讲解。

本篇总结


本篇着重讲解了talent-aio如何处理半包、粘包的情况,对输入进行解包,并处理输入数据包,并返回数据的。
在本系列的下一篇中,会讲解talent-aio的断线重连、keepalive等功能是如何实现的,并且接受其是如何定制线程以及executor的。最后,还将给出一个简单的使用talent-io的IM server的示例。预知后事如何,请听下回分解~

转:http://www.jianshu.com/p/6e3c4d99e72e

talent-aio源码阅读小记(二)的更多相关文章

  1. 【原】FMDB源码阅读(二)

    [原]FMDB源码阅读(二) 本文转载请注明出处 -- polobymulberry-博客园 1. 前言 上一篇只是简单地过了一下FMDB一个简单例子的基本流程,并没有涉及到FMDB的所有方方面面,比 ...

  2. 【原】AFNetworking源码阅读(二)

    [原]AFNetworking源码阅读(二) 本文转载请注明出处 —— polobymulberry-博客园 1. 前言 上一篇中我们在iOS Example代码中提到了AFHTTPSessionMa ...

  3. 【原】SDWebImage源码阅读(二)

    [原]SDWebImage源码阅读(二) 本文转载请注明出处 —— polobymulberry-博客园 1. 解决上一篇遗留的坑 上一篇中对sd_setImageWithURL函数简单分析了一下,还 ...

  4. 【详解】ThreadPoolExecutor源码阅读(二)

    系列目录 [详解]ThreadPoolExecutor源码阅读(一) [详解]ThreadPoolExecutor源码阅读(二) [详解]ThreadPoolExecutor源码阅读(三) AQS在W ...

  5. Redis源码阅读(二)高可用设计——复制

    Redis源码阅读(二)高可用设计-复制 复制的概念:Redis的复制简单理解就是一个Redis服务器从另一台Redis服务器复制所有的Redis数据库数据,能保持两台Redis服务器的数据库数据一致 ...

  6. Caddy源码阅读(二)启动流程与 Event 事件通知

    Caddy源码阅读(二)启动流程与 Event 事件通知 Preface Caddy 是 Go 语言构建的轻量配置化服务器.https://github.com/caddyserver/caddy C ...

  7. 【 js 基础 】【 源码学习 】backbone 源码阅读(二)

    最近看完了 backbone.js 的源码,这里对于源码的细节就不再赘述了,大家可以 star 我的源码阅读项目(source-code-study)进行参考交流,有详细的源码注释,以及知识总结,同时 ...

  8. Rpc框架dubbo-client(v2.6.3) 源码阅读(二)

    接上一篇 dubbo-server 之后,再来看一下 dubbo-client 是如何工作的. dubbo提供者服务示例, 其结构是这样的!dubbo://192.168.11.6:20880/com ...

  9. talent-aio源码阅读小记(一)

    近来在oschina上看到一个很火的java 即时通讯项目talent-aio,恰巧想了解一下这方面的东西,就阅读了一下项目的源码,这里对自己阅读源码后的一些心得体会做一下备忘,也希望能够对其他项目中 ...

  10. Tomcat源码阅读(二)初始化

    近来,我开始阅读tomcat的源码,感觉还挺清晰易懂:为了方便理解,我参考了网上的一些文章,把tomcat的组成归纳一下:整个tomcat的组成如下图所示: Tomcat在接收到用户请求时,将会通过以 ...

随机推荐

  1. python下载文件

    import urllib import urllib2 import requests url = "http://www.blog.pythonlibrary.org/wp-conten ...

  2. eclipse 创建 user library 方法

    1.Window - Preferences - Java - Build Path - User Libraries 2.新建 UserLibraries 3. 4.重复上一步依次添加需要的jar文 ...

  3. MySQL免安装版中 my-default.ini 的配置

    拷贝一份  “my-default.ini”  文件 重命名为 “my.ini” 这样根目录下就有两个.ini文件了 一个是my-default.ini 一个是my.ini 接下来我们只需修改my.i ...

  4. 中兴ZXR10 GER4核心路由器配置案例

    Connecting to 192.168.100.2:23...Connection established.To escape to local shell, press 'Ctrl+Alt+]' ...

  5. leetcode:回溯——permutation-sequence,

    1. permutation-sequence 顺序排列第k个序列 The set[1,2,3,…,n]contains a total of n! unique permutations. By l ...

  6. Selenium入门7 内嵌框架iframe

    如果网页内嵌iframe,那么iframe里的元素是无法直接定位的,需要使用switch_to.frame进入frame操作: 之后需要再操作页面上非嵌入在iframe里的元素,需要使用switch_ ...

  7. P1089 津津的储蓄计划

    题目描述 津津的零花钱一直都是自己管理.每个月的月初妈妈给津津300300元钱,津津会预算这个月的花销,并且总能做到实际花销和预算的相同. 为了让津津学习如何储蓄,妈妈提出,津津可以随时把整百的钱存在 ...

  8. theano中tensor的构造方法

    import theano.tensor as T x = T.scalar('myvar') myvar = 256 print type(x),x,myvar 运行结果: <class 't ...

  9. P3901 【数列找不同】

    这个题我们可以使用树状数组做 啥? 树状数组? 那个不是维护前缀和的东西吗? 各位看官,让我慢慢道来. 首先我们可以想到,对于一个询问$ [l,r] \(,只有\)[1,r]$中的数可能对这个询问有影 ...

  10. System.Web.UI.Page

    mdsn:点击查看此类介绍 git:   点击查看封装方法   消息弹框,消息弹框跳转,自定义脚本信息 定义:表示一个从托管 ASP.NET Web 应用程序的服务器请求的 .aspx 文件(也称为 ...