前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于muduo网络库的注解

关于muduo网络库的注解

作者头像
bear_fish
发布2018-09-19 11:53:46
7570
发布2018-09-19 11:53:46
举报
文章被收录于专栏:用户2442861的专栏

http://blog.csdn.net/liuxuejiang158blog/article/details/17056537#comments

  注:muduo用C++实现蛮有意思的,其大量使用boost的shared_ptr,bind,function实现对象生命期控制、事件回调机制,且基于对象编程而非面向对象编程。在此记点笔记吧,以备后查。

文字部分:

1 Reactor模式的实现:关键是三个类:Channel,Poller,EventLoop。

 class Channel:事件分发器,其记录了描述符fd的注册事件和就绪事件,及就绪事件回调比如可读回调readCallback。其和文件描述符fd是一一对应的关系,但其不拥有fd。当一个fd想要注册事件并在事件就绪时执行相应的就绪事件回调时,首先通过Channel::update(this)->EventLoop::updateChannel(Channel*)->Poller::updateChannel(Channel*)调用链向poll系统调用的侦听事件表注册或者修改注册事件。Channel作为是事件分发器其核心结构是Channel::handleEvent()该函数执行fd上就绪事件相应的事件回调,比如fd可读事件执行readCallback()。Channel应该还具有一个功能是:Channel::~Channel()->EventLoop::removeChannel(Channel*)->Poller::removeChannel(Channel*)将Poller中的Channel*移除防止空悬指针。这是因为Channel的生命周期和Poller/EventLoop不一样长。其关键数据成员:int fd_文件描述符,int events_文件描述符的注册事件,int revents_文件描述符的就绪事件,及事件回调readCallback_,writeCallback...

 class Poller:实现IO multiplexing,其功能仅仅是poll系统调用的简单封装,其生命周期和EventLoop一样长,Poller不拥有Channel支持有Channel*指针(因此必要时候需要Channel自己解注册以防空悬指针)。Poller的关键数据成员是:vector<struct pollfd> pollfds_事件结构体数组用于poll的第一个参数;map<int,Channel*> channels_用于文件描述符fd到Channel的映射便于快速查找到相应的Channel,如poll返回后遍历pollfds_找到就绪事件的fd再通过channels_找到fd的channel然后就可以通过Channel::handleEvent()执行就绪事件回调,值得注意的是Channel中已经记录了fd所以fd和Channel完成了双射。关键的成员函数:Poller::poll(int timeoutMs,vector<Channel*> activeChannels)其调用poll侦听事件集合,并在timoutMs时间内就绪的事件集合通过activeChannels返回。这里Poller::poll()在poll返回后本可以执行Channel::handleEvent()将就绪事件的回调执行了,但是并没有这样做的原因是,Channel::handleEvent()可能修改Poller的两个容器,即添加或删除Channel*,在遍历容器的时候修改容器是非常危险的,同时为了简化Poller,Poller的职责仅仅是IO复用,至于事件分发还是交给Channel自己完成。  class EventLoop: 事件循环。先看一个调用链:EventLoop::loop()->Poller::poll()通过此调用链获得一个vector<Channel*> activeChannels_的就绪事件集合,再遍历该容器,执行每个Channel的Channel::handleEvent()完成相应就绪事件回调。至此一个完整的Reactor模式即完成。注意这里的Reactor遵循one loop per thread即所在一个线程中完成,故并没有涉及到线程同步机制,以后可能会有其它线程调用这三个类,则通过线程转移函数将一些操作转移到一个线程中完成。(若一个函数既可能加锁情况下使用有可能在未加锁情况下使用,那么就拆成两个函数,需要加锁的函数去调用不需要加锁的函数。线程转移实现就可以通过两个函数实现,如:假设类one隶属于线程B,线程A调用one的方法fun,fun向one注册一个回调,从而将具体操作转移到one的所属线程B中去执行。) 2 定时器: 主要有几个类,Timer定时器包含超时回调,TimerId定时器加上一个唯一的ID,Timestamp时间戳,TimerQueue管理所有的定时器。传统的定时通过select/poll实现,现在通过timerfd实现定时,采用文件描述符实现定时将有利于统一事件源。这些将为EventLoop实现定时功能。 Timer:定时器,具有一个超时时间和超时回调。超时时间由当前时间戳加上一个超时时间生成一个绝对时间。定时器回调函数timerCallback。 TimerQueue: 定时器队列,用于管理所有的定时器,当定时器超时后执行相应的Timer::run()定时器回调。采用set<pair<TimeStamp,Timer*> >存储所有未超时的定时器,这里采用pair<TimeStamp,Timer*>的原因是在一个时间点可能有多个时间戳TimeStamp超时,而查找只返回一个。通过给timerfd一个超时时间实现超时计时,通过Channel管理timerfd,然后向EventLoop和Poller注册timerfd的可读事件,当timerfd的可读事件就绪时表明一个超时时间点到了,TimerQueue::handleRead()遍历set容器找出那些超时的定时器并执行Timer::run()实现超时回调。timerfd怎么实现多个定时器超时计时的呢?每次向set插入一个定时器Timer的时候就比较set的头元素的超时时间,若新插入的超时时间小,则更新timerfd的时间,从而保证timerfd始终是set中最近的一个超时时间。当timerfd可读时,需要遍历容器set,因为可能此时有多个Timer超时了(尽管tiemrfd是当前最小的定时时间)。为了复用定时器,每次执行完定时器回调后都要检查定时器是否需要再次定时。这里的关键是采用timerfd实现统一事件源。 3 class EventLoop的改动,实现用户定时回调:当有了定时器TimerQueue后,EventLoop就可以实现几个定时器接口:EventLoop::runAt(TimeStamp,TimerCallback)在一个绝对时间执行一个回调TimerCallback;EventLoop::runAfter(double delay,TimerCallback)实现一个相对时间回调,其内部实现是当前时间戳TimeStamp加上delay后形成一个绝对时间戳然后调用EventLoop::runAt(); EventLoop::runEvery(double interval,TimerCallback)实现周期回调,这里将使用到TimerQueue执行完超时回调后会检查定时器是否需要再次定时的功能。 4 class EventLoop的改动,实现用户指定任务回调:EventLoop::runInLoop(boost::function<void()>),若是EventLoop隶属的线程调用EventLoop::runInLoop()则EventLoop马上执行;若是其它线程调用则执行EventLoop::queueInLoop(boost::function<void()>将任务添加到队列中(这里就是前面说的线程转移)。EventLoop如何获得有任务这一事实呢?通过eventfd可以实现线程间通信,具体做法是:其它线程向EventLoop::vector<boost::function<void()> >添加任务T,然后通过EventLoop::wakeup()向eventfd写一个int,eventfd的回调函数EventLoop::handleRead()读取这个int,从而相当于EventLoop被唤醒,此时loop中遍历队列执行堆积的任务。这里采用Channel管理eventfd,Poller侦听eventfd体现了eventfd可以统一事件源的优势。 5 实现线程安全的class TimerQueue:原来添加定时器的调用链:TimerQueue::addTimer()->TimerQueue::insert()实现添加的,但是这只能实现TimerQueue所属的线程执行,若其它线程想向此IO线程添加一个定时任务是不安全的。          为了实现添加定时器Timer到set的线程安全性,将定时器添加函数TimerQueue::addTimer()分拆为两部分:TimerQueue::addTimer()只负责转发,addTimerInLoop()实现具体的定时器添加。具体的调用链为:TimerQueue::addTimer()->EventLoop::runInLoop(TimerQueue::runInLoop)->TimerQueue::runInLoop()->TimerQueue::insert(),可以看出通过把TimerQueue::runInLoop()这个回调任务添加EventLoop::runInLoop()中从而实现将添加定时器这一操作转移到IO线程来做。TimerQueue::insert()插入一个新的定时器后将检查当前最近的超时时间,若最近的超时时间变了则重置timerfd的计时。 6 class  EventLoopThread: 启动一个线程执行一个EventLoop,其语义和"one loop per thread“相吻合。注意这里用到了互斥量和条件变量,这是因为线程A创建一个EventLoopThread对象后一个运行EventLoop的线程已经开始创建了,可以通过EventLoopThread::startLoop()获取这个EventLoop对象,但是若EventLoop线程还没有创建好,则会出错。所以在创建EventLoop完成后会执行condititon.notify()通知线程A,线程A调用EventLoopThread::startLoop()时调用condition.wai()等待,从而保证获取一个创建完成的EventLoop.毕竟线程A创建的EventLoop线程,A可能还会调用EventLoop执行一些任务回调呢。 7 class Acceptor: 用于accept一个TCP连接,accept接受成功后通知TCP连接的使用者。Acceptor主要是供TcpServer使用的,其生命期由后者控制。一个Acceptor相当于持有服务端的一个socket描述符,该socket可以accept多个TCP客户连接,这个accept操作就是Acceptor实现的。            这里封装了一些常用的网络相关的数据结构和操作,如class InetAddress表示sockaddr_in的封装,如可以通过ip地址和port端口生成一个sockaddr_in; class Socket封装了部分关于socket套接字的操作,如Socket::bindAddress(InetAddress&)将socket和一个sockaddr_in地址绑定,Socket::accept(InetAddress& peerAddr)将一个socket允许连接一个客户端地址peerAddr,Socket::listen()监听socket,Socket::shutdownWrite()实现关闭socket的写。               Acceptor在构造的时候会创建一个socket描述符acceptSocket_(这是一个Socket类型即socket的RAII封装),并通过一个Channel(注册事件及回调函数)管理acceptSocket_::fd成员(即socket描述符),一旦该socket可读即有TCP客户连接请求,则Channel::handleEvent()将会调用Acceptor::hanleRead()执行accept一个TCP客户连接。Acceptor::handleRead()还会将新的TCP客户连接和客户端地址通过回调函数newConnectionCallback(connfd,peerAddr)传给该TCP客户连接的使用者,通常是TcpServer类,这里的回调函数newConnectionCallback是在Acceptor::setNewConnectionCallback(newConnectionCallback)指定的。值得注意的是这里又是统一事件源的思想,即通过Channel和Poller管理事件。Acceptor::listen()的工作是:启动acceptSocket_::listen()监听socket描述符,并通过Channel::enableReading()将socket的可读事件注册到Poller的事件集合中。 8 class TcpServer: 管理所有的TCP客户连接,TcpServer供用户直接使用,生命期由用户直接控制。用户只需设置好相应的回调函数(如消息处理messageCallback)然后TcpServer::start()即可。             这里先假设每个TCP客户连接由一个类TcpConenction管理(具体执行消息的接收发送之类的),而TcpServer的工作就是管理这些TcpConenction,TcpConnection将在后面给出。假设TcpServer持有boost::scoped_ptr<TcpConnection>的指针TcpConnectionPtr。               TcpServer在构造时接收一个由IP地址和port构成的InetAddress参数,并将此地址传给Acceptor用于接收该地址的TCP连接请求。              TcpServer持有scoped_ptr<Acceptor> acceptor_用于接收TcpServer监听端口上的TCP连接请求,注意Accpetor每次accept连接后都要将新连接的描述符connfd和地址peerAddr返回给使用者,这里TcpServer在构造时通过accptor_->setNewConnectionCallback(bind(&TcpServer::newConnection,this,_1,_2))将TcpServer::newConnection传给Acceptor,acceptor_在接受TCP客户连接后将调用TcpServer::newConnection(connfd,peerAddr),而TcpSrever::newConnection()的主要功能就是为<connfd,peerAddr>创建一个TcpConnection管理该TCP客户连接,并向TcpConnection注册一些回调函数,比如:connectionCallback主要是在TcpServer中由用户指定的一些连接处理函数最后一路经由TcpSrever传到TcpConnection中才被调用,此外还有用户指定的消息处理回调等都是经由TcpServer传给TcpConnection中去具体执行。此外TcpServer::newConnection()中还会执行TcpConnection::connectEstablished()该函数将会使这个具体的TcpConnection连接对应的描述符connfd加入poll的事件表,即也是通过一个Channel管理一个具体的TCP客户连接。用户向TcpServer注册连接回调函数的调用链:用户在创建TcpServer后TcpServer::setConnectionCallback()接收用户注册的连接回调函数;同时在TcpServer创建时会向Acceptor注册回调:TcpServer::TcpServer()->Acceptor::setNewConnecioncallback()后有新TCP连接Acceptor接受连接,并执行回调给连接使用者:Acceptor::handelRead()->newConnection()/Tcpserver::newConnection()->TcpConnection::connectEstablished()/并向TcpConnection注册用户注册的Callback函数。               TcpServer采用map<string,TcpConnectionPtr>管理所有的TCP客户连接,其中string是由TcpServer的服务端地址加上一个int构成表示TcpConnectionPtr的名字。               TcpServer中由用户指定的回调有:connectionCallback当TcpConenction建立时调用(由TcpConnection::connectEstablished()调用connectionCallback())用于执行用户指定的连接回调。messageCallback当TcpConenction有网络消息的时候执行该函数由Channel::handleEvent()->TcpConnection::handleRead()->messageCallback()。writeCompleteCallback由用户指定的当TCP连接上的消息发送完毕时执行的回调。这些函数都是用户在TcpServer创建后通过TcpServer::set*Callback系列函数注册的。当Acceptor接受一个新的TCP连接时执行Acceptor::handleRead()->TcpServer::newConnection()->TcpConnection::set*Callback()这样完成用于指定函数的传递。那么执行呢?这个要在TcpConenction对应的socket事件就绪时可读/可写时由Channel::handEvent()执行这些用户指定的回调。               TcpServer::removeConnection()主要功能从TcpServer中移除一个TcpConnection,但是不能直接移除,而要通过线程转移函数完成。TcpServer::removeConenction()将执行EventLoop::runInLoop(bind(&TcpServer::removeConnectionInLoop)->EventLoop::runInLoop()->TcpServer::removeConnectionInLoop()                TcpServer::removeConenctionInLoop()将一个TcpConnection从TcpServer中移除,并向EventLoop注册回调EventLoop::runInLoop(bind(&TcpConenction::connectDestroyed)),然后执行TcpConnection::connectDestroyed()。 9 class TcpConnection: 用于管理一个具体的TCP客户连接,比如消息的接收与发送,完成用户指定的连接回调connectionCallback。这里采用shared_ptr管理TcpConnection,因此其public继承boost::enable_shared_from_this<TcpConnection>。               TcpConnection构造时接收参数有TCP连接的描述符sockfd,服务端地址localAddr,客户端地址peerAddr,并通过Socket封装sockfd。且采用Channel管理该sockfd,向Channel注册TcpConection的可读/可写/关闭/出错系列回调函数,用于Poller返回就绪事件后Channel::handleEvent()执行相应事件的回调。               TcpConnection有四个状态:kConnecting正在连接,kConnected已连接,kDisconnecting正在断开,kDisconnected已断开。               TcpConnection:有一些列函数用于TcpServer为连接指定事件回调函数,如TcpConnection::setConnectionCallback/setCloseback等是在TcpServer::newConnection()中注册的回调函数,并且当Acceptor接受一个新TCP连接后执行回调TcpServer::newConnection(),该回调创建一个TcpConenction对象并将用户指定的回调函数通过TcpConnection::set*Callback函数传给TcpConneciton。              TcpConnection有一些列函数用户处理sockfd上的事件回调函数,如TcpConnection::handleRead()是在Poller返回sockfd可读事件时由Channel::handleEvent()调用的。类似还有TcpConnection::handleWrite()等。              TcpConnection::send(string& message)->EventLoop::runInLoop(bind(&TcpConnection::sendInLoop(string& message))->EventLoop::doPendingFunctors()->TcpConnection::sendInLoop(string& message)保证消息发送的线程安全,后者通过write系统调用发送消息。              TcpConnection::shutdown()->EventLoop::runInLoop(bind(&TcpConnection::shutdownInLoop())->EventLoop::doPendingFunctors()->TcpConnection::shutdownInLoop()类似上面,通过线程转移操作实现安全关闭TCP连接。               TcpConnection中增加了用户指定系列回调函数conenctionCallback.messageCallback,writeCompleteCallback这些都是用户通过TcpServer传给TcpConnection,在TcpServer中已经描述过了。当Poller返回TcpConenction对应的Socket就绪事件时Channel::handleEvent()->TcpConnection::handle些列函数->执行这一些列回调。                TcpConnection::closeCallback()不是给用户使用的,而是通知TcpServer或TcpClient移除它们容器中的TcpConnectionPtr。该函数如何设定的呢?当Acceptor接受一个TCP连接时:Channel::handelEvent()->Acceptor::handleRead()->TcpServer::newConenction()中新建一个TcpConnection并通过TcpConnection::setCloseCallback(bind(&TcpSerer::,removeConenction,this,_1))这样才完成将TcpServer::removeChannel()函数传递给TcpConnection::closeCallback()。closeCallback()何时执行呢?当由Channel管理的TcpConnection对应的Socket发生POLLHUP事件(该事件由Poller返回)就绪时,Channel::handleEvent()->TcpConnection::handleClose()->TcpConnection::closeCallback()->TcpServer::removeConnection()。                 TcpConnection::connectEstablished()连接建立回调函数(不是用户通过TcpServer指定的connectionCallback),该函数主要的功能:调用Channel::enableReading()将TcpConnection对应的Socket注册到Poller的事件表,执行用户指定的connectionCallback,并将TcpConnection状态置为kConnected。该函数何时被执行呢?回忆前面的Acceptor持有Tcpserver对应的服务端侦听描述符listenfd(由Channel管理),当listenfd可读表明有TCP连接请求,此时Channel::handleEvent()->Acceptor::handleRead()->TcpServer::newConnection()->EventLoop::runInLoop(bind(&TcpConnection::connectEstablished))->EventLoop::queueInLoop()->EventLoop::loop()->EventLoop::doPendingFunctors()->TcpConnection::connectEstablished()。可见TcpServer也是通过向EventLoop::runInLoop添加Tcpconnection::conectEsatablished回调,表明TcpServer可TcpConencion可能不再同一个线程,需要通过线程转移来实现调用。                 TcpConenction::connectDestroyed()是TcpConenction析构前调用的最后一个函数,用于通知用户连接已断开。其只要功能是:将TcpConenction状态设为kDisconnected;Channel::disableAll()解除TcpConnection的事件注册,EventLoop::removeChannel()移除该管理TcpConnection的Channel;执行用于指定的回调conenctionCallback。该函数如何调用的呢?这要追溯到TcpServer::newConnection()将TcpServer::removeConenction注册到TcpConnection::closeCallback中,当TcpConnection对应的Socket的POLLHUP事件触发时执行TcpConenction::handleClose()->closeCallback()/TcpServer::removeConenction()->EvetnLoop::runInLoop()->TcpServer::removeInLoop()->EventLoop::runInLoop(bind(&TcpConnection::connectDestroyed))->TcpConnection::connectDestroyed()。                TcpConnection::shutdown()用使用者执行关闭TcpConenction,TcpConnection::shutdown()->EventLoop::runInLoop()->TcpConnection::shutdownInLoop()->socket::shutdown(sockfd,SHUT_WR)//SHUT_WR表示以后的发送将被丢弃。                TcpConnection::handleRead()被Channel::handleEvent()可读事件调用,它的主要工作是通过readv()将socket上的数据读取到Buffer中,并执行用于指定的消息回调messageCallback()。                TcpConnection::handleWrite():被Channel::handleEvent()的可写事件调用,通过write()将Buffer的数据发送出去,若Buffer的数据一次性发送完毕,则执行用户指定的回调writeCompleteCallback(),若一次没有发送完毕,则poll和epoll的LT模式会反复触发可写事件的,所以下次还有机会发送剩余数据。                TcpConnection::handleClose()主要执行Channel::disableAll()和closeCallback()。                TcpConnection有连个Buffer(后面会提到),inputBuffer_,outputBuffer_管理TcpConenction上的数据接收与发送。inputBuffer由TcpConnection::handleRead()调用(Buffer通过readv集中从fd集中读到内存中)。outputBuffer由TcpConnection::handleWrite()通过write()发送到fd上。                TcpConnection::send()->EventLoop::runInLoop()->TcpConenction::runInLoop(),send()可以用户或者其它线程调用,用于发送消息message。这个函数需要先执行线程安全转移到TcpConenction所在的IO线程执行runInLoop()。runInLoop()函数的功能:首先检查TcpConneciton对应的Socket是否注册了可写事件,若注册了可写事件表明outputBuffer_中已经有数据等待发送,为了保证顺序这次的数据只好outputBuffer_.appen()到Buffer中通过Poller返回POLLOUT事件时Channel::handleEvent()->TcpConenction::handleWrite()来发送outputBuffer_的堆积数据。如果Channel::isWriting()返回false则表明此Socket没有向Poller注册POLLOUT事件也就此前没有数据堆积在outputBuffer_中,此次的消息message可以直接通过write发送,但是如果write没有一次性发送完毕,那么message剩余的数据仍要outputBuffer_::append()到Buffer中,并向Poller注册此Socket的POLLOUT事件,以通过TcpConnection::handleWrite()来发送outputBuffer_的堆积数据。无论是sendInLoop()->write还是Channel::handleEvent()->handleWrite(),只要确定发送完message或者outputBuffer_中的数据,那么都要调用用户指定的回调writeCompleteCallback()。                  此外TcpConenction还需要忽略SIGPIPE信号,做法是在TcpConenction.cc中定义一个IngoreSigPipe类构造时signal(SIGPIPE,SIG_IGN)。                 TcpConnection::setTcpNoDelay()->socketopt(..,TCP_NODELAY..)来关闭Nagle算法。 10  到了这步,EventLoop和Poller都应该具备成员函数removeChannel()用于移除那些管理TcpConenction等的Channel。这里Poller有个成员vector<struct pollfd> pollfds_当移除Channel时有个trick值得注意:先将要移除的Channel::fd()的pollfd和pollfds_的最后一个元素交换swap()然后再调用pollfds_.pop_back可以避免vector删除时元素的移动。这样删除操作的复杂度为O(1)。 11   class Buffer应用层缓冲区:在non-blocking+IO multiplexing中应用层缓冲区是必须的。例如:TcpConection向发送100Kb数据,但是write只发送80Kb,剩下20Kb肯定要阻塞线程等待发送了,这和non-blocking矛盾,因此需要设计Buffer充当中间件置于应用层和底层write/read间从而实现non-blocking。这样,应用层只管生成或者读取数据,至于怎样存取数据和数据量则由Buffer完成。Buffer底层是vector<char>,有一个readerIndex和writerIndex分别表示可读位置和可写位置,这两个位置内的区间表示Buffer已有的数据。值得注意的是Buffer的两个trick:每次读取fd上的数据时通过readv一部分读取到Buffer中,一部分读取到找空间char extrabuf[65535]中,若Buffer装满了即extrabuf中有数据,则需要extrabuf中的数据append到Buffer中,这样做可以在初始时每个连接的Buffer的避免过大造成内存浪费,也避免反复调用read的系统开销,每次Buffer不够时通过extrabuf再append到Buffer中使Buffer慢慢变大;还有一个就是Buffer提供了一个前向空间,在消息序列化完毕时可以通过prepend()将消息的大小添加的Buffer的头部。另外Buffer的readerIndex和writerIndex都是移动的,只要在Buffer的空闲空间不够时才加大Buffer的vector,否则可以通过内部腾挪方式即让readerIndex和writerIndex向前移动(数据也跟着移动)这样Buffer就不增大vector.size(). 12 class TcpServe的改进:  TcpServer有自己的一个EventLoop用来接收新的TCP客户连接,然后从event loop pool中选一个loop给TCP客户连接(即TcpConnection)。这就需要使用class EventLoopThreadPool来创建多个线程每个线程一个EventLoop(one loop per thread)。               TcpServer::newConnection()在创建一个TcpConnection后从EventLoopTreadPool中选一个EventLoop给这个TcpConnection。

              TcpServer::removeConnection()需要拆分成两个函数,因为现在TcpServer和TcpConenction可能不再同一个线程里了,需要通过线程转移函数将移除操作转移到TcpConneciton的IO线程中去。TcpServer::removeConnection()->EventLoop::runInLoop()->TcpServer::removeConnectionInLoop()->EventLoop::runInLoop()->TcpConnection::connectDestroyed()。Tcpserver中erase掉这个TcpConnectionPtr。

13 class Connector:用于发起连接,当socket变得可写时表示连接建立完毕,其间需要处理各种类型的错误。connect返回EAGAIN是真的错误表示暂时没有端口可用,要关闭socket稍后再试;EINPROGRESS是“正在连接”,即使socket可写,也需要用getsockopt(sokfd,SOL_SOCKET,SO_ERROR...)再次确认。超时重连的时间应逐渐延长,需要处理自连接的情况。Connector只负责建立连接,不负责建立TcpConnection,它有一个建立连接回调函数由用户指定(Connector基本是TCP客户端使用,且一个客户端一个Conenctor)。

           Connector有三个状态:kDisconnected未连接,kConnecting正在连接,kConnected已连接。

           Connector构造时指定一个服务端地址InetAddress和一个事件循环EventLoop,状态设为kDisConnected。指定一个最大重试连接时间。

           Connector::start()可以由其它线程调用,该函数内部执行EventLoop::runInLoop(bind(&Connector::startInLoop,this))将通过EventLoop将操作转移到Connector的线程中去。

           Connector::startInLoop()判断此Connector还没有连接,则调用Connector::connect()

           Connector::connect()创建一个sockfd,并调用connect(sockfd,&serverAddress,sizeof(serverAddress)),然后返回一个errno,根据errno的值进行进一步选择是关闭连接,重师连接还是调用已连接函数。

            连接返回errno为EAGAIN则调用Connector::retry()该函数调用EventLoop::runAfter()在一段时间间隔后重试连接。

            errno为EINPROGRESS表示正在连接,则调用Connector::connecting()该函数将该为该连接设置一个Channel来管理连接,并向Channel注册Connector::handleWrite,Conenctor::handleError的回调函数。其中Connector::handleWrite()当正在连接kConnecting则用需要测试该连接(已经可写了还kConencting)可能需要进一步重新连接即调用Connector::retry()注意这时候socketfd需要重新分配了,而Conenctor是可以重复使用的。Cionnector::handleError()执行Connector::removeAndResetChannel()和Connector::retry()重试连接。

            当用户或其它线程调用Connector::start()->EventLoop::runInLoop()->Connector::startInLoop()->Connector::connect()根据errnor执行下面的情形:

EAGAIN:Connector::retry()->EventLoop::runAfter()延迟重连->Conncetor::startInLoop()

EACCESS/EPERM/EBADF:  close(sockfd)

EINPROGRESS:Connector::connecting()该函数向Channel注册回调函数并Channel::enableWriting()关注这个正在连接的socketfd是否可写。

            此后当处于“正在连接kConnecting”的sockfd事件就绪时:Channel::handelEvent()->Connector::handleWrite()/Connector::handleError()

             Connector::handleWrite()若检测Connector状态仍在kConnecting时需要调用getsocketopt(sockfd,SOL_SOCKET,SO_ERROR...)检测,若返回0则执行用户指定的连接回调函数Connector::newConnectionCallback()。

             Connector::handleError()->Conenctor::retry()

14 class TcpClient:每个TcpClinet只管理一个Connector。其内容和TcpServer差不多,TcpClient具备TcpConnection断开连接后重新连接的功能。

             TcpClient构造时new一个Connector,并指定一个EventLoop。用户要指定的connectionCallback,messageCallback回调函数。并设置Connector::setNewConnection(bind(&TcpClient::newConnection,this,_1))将连接建立回调赋给Connector::newConnectionCallback。

             用户调用TcpClient::connect()发起连接->Conenctor::start()->TcpClient::newConnection().

              TcpClinet::newConnection()将new一个TcpConneciton对象conn并设置TcpConnection::setConnecitonCallback/setMessageCallback/setWriteCompleteCallback/setCloseCallback等回调函数。其中setConnectionCallback将用户指定的ConnectionCallback传给TcpConenciton,setMessageCallback将TcpClient中用户指定的messageCallback传给TcpConneciton。TcpConnection::closeCallback是TcpClient::removeConenction。最后TcpClient::newConneciton()将会调用TcpConnection::connectEstablished()。

              TcpClient::removeConnection(),由于TcpClient只管理一个Connector也就是一个TcpConenction它们都在一个线程中,所以不涉及操作线程转移。TcpClient::removeConenction()->EventLoop::queueInLoop()->TcpConnection::connectDestroyed().若有重连的必要将执行Connector::restart()。

14  class Epoller和Poller差不多。

代码部分:

注意这里的代码没有muduo网络库全,挂在这里只是做了些注释,算是留个尸体吧。如有必要请参看muduo。

[cpp] view plain copy

  1. #include<iostream>
  2. #include<map>
  3. #include<string>
  4. #include<vector>
  5. #include<utility>
  6. #include<set>
  7. #include<deque>
  8. #include<algorithm>
  9. #include<boost/any.hpp>
  10. #include<boost/enable_shared_from_this.hpp>
  11. #include<boost/noncopyable.hpp>
  12. #include<boost/scoped_ptr.hpp>
  13. #include<boost/shared_ptr.hpp>
  14. #include<boost/weak_ptr.hpp>
  15. #include<boost/function.hpp>
  16. #include<boost/static_assert.hpp>
  17. #include<boost/bind.hpp>
  18. #include<boost/foreach.hpp>
  19. #include<boost/ptr_container/ptr_vector.hpp>
  20. #include<errno.h>
  21. #include<fcntl.h>
  22. #include<stdio.h>
  23. #include<strings.h>
  24. #include<unistd.h>
  25. #include<endian.h>
  26. #include<assert.h>
  27. #include<stdio.h>
  28. #include<stdlib.h>
  29. #include<string.h>
  30. #include<pthread.h>
  31. #include<unistd.h>
  32. #include<poll.h>
  33. #include<errno.h>
  34. #include<signal.h>
  35. #include<stdint.h>
  36. #include<arpa/inet.h>
  37. #include<netinet/tcp.h>
  38. #include<netinet/in.h>
  39. #include<sys/timerfd.h>
  40. #include<sys/syscall.h>
  41. #include<sys/time.h>
  42. #include<sys/eventfd.h>
  43. #include<sys/types.h>
  44. #include<sys/socket.h>
  45. #include<sys/epoll.h>
  46. using namespace std;  
  47. using namespace boost;  
  48. # define UINTPTR_MAX       (4294967295U)//一个无符号大数
  49. /*
  50. *互斥量
  51. */
  52. class Mutex:noncopyable{  
  53. public:  
  54.         Mutex(){  
  55.             pthread_mutex_init(&mutex,NULL);  
  56.         }  
  57. void lock(){  
  58.             pthread_mutex_lock(&mutex);  
  59.         }  
  60. void unlock(){  
  61.             pthread_mutex_unlock(&mutex);  
  62.         }  
  63.         pthread_mutex_t& get(){  
  64. return mutex;  
  65.         }  
  66. private:  
  67.         pthread_mutex_t mutex;  
  68. };  
  69. /*
  70. *互斥量RAII
  71. */
  72. class MutexLockGuard:noncopyable{  
  73. public:  
  74. explicit MutexLockGuard(Mutex& mutex):mutex_(mutex){  
  75.             mutex_.lock();  
  76.         }  
  77.         ~MutexLockGuard(){  
  78.             mutex_.unlock();  
  79.         }  
  80. private:  
  81.         Mutex& mutex_;  
  82. };  
  83. /*
  84. *条件变量
  85. */
  86. class Condition:noncopyable{  
  87. public:  
  88. explicit Condition(Mutex& mutex):mutex_(mutex){  
  89.             pthread_cond_init(&pcond_,NULL);  
  90.         }  
  91.         ~Condition(){  
  92.             pthread_cond_destroy(&pcond_);  
  93.         }  
  94. void wait(){  
  95.             pthread_cond_wait(&pcond_,&mutex_.get());  
  96.         }  
  97. void notify(){  
  98.             pthread_cond_signal(&pcond_);  
  99.         }  
  100. void notifyALL(){  
  101.             pthread_cond_broadcast(&pcond_);  
  102.         }  
  103. private:  
  104.         Mutex& mutex_;  
  105.         pthread_cond_t pcond_;  
  106. };  
  107. /*
  108. *倒计时闩
  109. */
  110. class CountDownLatch{  
  111. public:  
  112.         CountDownLatch(int count):mutex_(),condition_(mutex_),count_(count){}  
  113. void wait(){  
  114.             MutexLockGuard lock(mutex_);  
  115. while(count_>0)  
  116.                 condition_.wait();  
  117.         }  
  118. void countDown(){  
  119.             MutexLockGuard lock(mutex_);  
  120.             --count_;  
  121. if(count_==0)  
  122.                 condition_.notifyALL();  
  123.         }  
  124. private:  
  125. mutable Mutex mutex_;  
  126.         Condition condition_;  
  127. int count_;  
  128. };  
  129. /*
  130.  *线程类Thread
  131.  */
  132. __thread pid_t t_cacheTid=0;//线程私有数据线程ID避免通过系统调用获得ID
  133. class Thread:noncopyable{  
  134. public:  
  135. typedef function<void()> ThreadFunc;//线程需要执行工作函数
  136. explicit Thread(const ThreadFunc& a,const string& name=string()):started_(false),  
  137.             joinded_(false),pthreadID_(0),tid_(new pid_t(0)),func_(a),name_(name){  
  138.             }  
  139.         ~Thread(){  
  140. if(started_&&!joinded_){  
  141.                 pthread_detach(pthreadID_);//分离线程
  142.             }  
  143.         }  
  144. void start();  
  145. /*
  146.         {
  147.             assert(!started_);
  148.             started_=true;
  149.             if(pthread_create(&pthreadID_,NULL,&startThread,NULL)){
  150.                 started_=false;
  151.                 abort();//终止进程刷新缓冲区
  152.             }
  153.         }
  154.         *///###1###使用此处会出错详见http://cboard.cprogramming.com/cplusplus-programming/113981-passing-class-member-function-pthread_create.html  
  155. void join(){//等待线程执行完工作函数
  156.             assert(started_);  
  157.             assert(!joinded_);  
  158.             joinded_=true;  
  159.             pthread_join(pthreadID_,NULL);  
  160.         }  
  161.         pid_t tid() const{  
  162. if(t_cacheTid==0){//如果没有缓存t_cacheTid则获取线程ID否则直接通过线程私有数据返回ID减少系统调用
  163.                 t_cacheTid=syscall(SYS_gettid);  
  164.             }  
  165. return t_cacheTid;  
  166.         }  
  167. const string& name() const{  
  168. return name_;  
  169.         }  
  170. //void* startThread(void* arg){//###1###
  171. void startThread(){  
  172.             func_();  
  173.         }  
  174. private:  
  175. bool started_;  
  176. bool joinded_;  
  177.         pthread_t pthreadID_;  
  178.         shared_ptr<pid_t> tid_;  
  179.         ThreadFunc func_;  
  180.         string name_;  
  181. };  
  182. void* threadFun(void* arg){//采用间接层执行工作函数
  183.     Thread* thread=static_cast<Thread*>(arg);  
  184. thread->startThread();  
  185. return NULL;  
  186. }  
  187. void Thread::start(){  
  188.     assert(!started_);  
  189.     started_=true;  
  190. if(pthread_create(&pthreadID_,NULL,threadFun,this)){  
  191.         started_=false;  
  192.         abort();//终止进程刷新缓冲区
  193.     }  
  194. }  
  195. /*
  196.  * 线程局部数据TSD
  197.  */
  198. template<typename T>  
  199. class ThreadLocal:noncopyable{  
  200. public:  
  201.         ThreadLocal(){  
  202.             pthread_key_create(&pkey_,&destructor);//每个线程会设定自己的pkey_并在pthread_key_delete执行destructor操作
  203.         }  
  204.         ~ThreadLocal(){  
  205.             pthread_key_delete(pkey_);//执行destructor操作
  206.         }  
  207.         T& value(){//采用单件模式,此处不会跨线程使用故不存在非线程安全的singleton问题
  208.             T* perThreadValue=static_cast<T*>(pthread_getspecific(pkey_));  
  209. if(!perThreadValue){  
  210.                 T* newObj=new T();  
  211.                 pthread_setspecific(pkey_,newObj);  
  212.                 perThreadValue=newObj;  
  213.             }  
  214. return *perThreadValue;  
  215.         }  
  216. private:  
  217. static void destructor(void* x){//清除私有数据
  218.             T* obj=static_cast<T*>(x);  
  219. delete obj;  
  220.         }  
  221. private:  
  222.         pthread_key_t pkey_;  
  223. };  
  224. /*
  225.  * 线程池
  226.  */
  227. class ThreadPool:noncopyable{  
  228. public:  
  229. typedef function<void()> Task;//线程工作函数
  230. explicit ThreadPool(const string& name=string()):mutex_(),cond_(mutex_),name_(name),running_(false){  
  231.         }  
  232.         ~ThreadPool(){  
  233. if(running_){  
  234.                 stop();//等待所有线程池中的线程完成工作
  235.             }  
  236.         }  
  237. void start(int numThreads){  
  238.             assert(threads_.empty());  
  239.             running_=true;  
  240.             threads_.reserve(numThreads);  
  241. for(int i=0;i<numThreads;i++){  
  242.                 threads_.push_back(new Thread(bind(&ThreadPool::runInThread,this)));//池中线程运行runInThread工作函数
  243.                 threads_[i].start();  
  244.             }  
  245.         }  
  246. void stop(){  
  247.             running_=false;//可以提醒使用者不要在此后添加任务了,因为停止池但是池还要等待池中线程完成任务
  248.             cond_.notifyALL();//唤醒池中所有睡眠的线程
  249.             for_each(threads_.begin(),threads_.end(),bind(&Thread::join,_1));//等待池中线程完成
  250.         }  
  251. void run(const Task& task){  
  252. if(running_){//###4###防止停止池运行后还有任务加进来
  253. if(threads_.empty()){//池中没有线程
  254.                     task();  
  255.                 }  
  256. else{  
  257.                     MutexLockGuard guard(mutex_);//使用RAII mutex保证线程安全
  258.                     queue_.push_back(task);  
  259.                     cond_.notify();  
  260.                 }  
  261.             }  
  262. else{  
  263.                 printf("线程池已停止运行\n");  
  264.             }  
  265.         }  
  266. bool running(){//使用者可以获取线程池的运行状态
  267. return running_;  
  268.         }  
  269. private:  
  270. void runInThread(){//线程工作函数
  271. while(running_){//###2###
  272.                 Task task(take());  
  273. if(task){//task可能意外的为NULL
  274.                     task();  
  275.                 }  
  276.             }  
  277.         }  
  278.         Task take(){  
  279.             MutexLockGuard guard(mutex_);  
  280. while(queue_.empty()&&running_){//###3###和###2###不能保证在池停止运行但是线程还没有完成操作期间安全。假设此期间有任务添加到池中,且某个线程A执行到###2###后马上被切换了,池running_=false停止运行,A被切换后运行执行###3###处无意义啊,因为池已经停止运行了。所以###4###是有必要提醒使用者池停止这一情景
  281.                 cond_.wait();//池中没有任务等待
  282.             }  
  283.             Task task;  
  284. if(!queue_.empty()){  
  285.                 task=queue_.front();  
  286.                 queue_.pop_front();  
  287.             }  
  288. return task;  
  289.         }  
  290.         Mutex mutex_;  
  291.         Condition cond_;  
  292.         string name_;  
  293.         ptr_vector<Thread> threads_;//智能指针容器
  294.         deque<Task> queue_;  
  295. bool running_;  
  296. };  
  297. /*
  298.  * 原子类型
  299.  */
  300. template<typename T>  
  301. class AtomicIntegerT : boost::noncopyable  
  302. {  
  303. public:  
  304.         AtomicIntegerT()  
  305.             : value_(0){}  
  306.         T get() const
  307.         {  
  308. return __sync_val_compare_and_swap(const_cast<volatile T*>(&value_), 0, 0);  
  309.         }  
  310.         T getAndAdd(T x)  
  311.         {  
  312. return __sync_fetch_and_add(&value_, x);  
  313.         }  
  314.         T addAndGet(T x)  
  315.         {  
  316. return getAndAdd(x) + x;  
  317.         }  
  318.         T incrementAndGet()  
  319.         {  
  320. return addAndGet(1);  
  321.         }  
  322. void add(T x)  
  323.         {  
  324.             getAndAdd(x);  
  325.         }  
  326. void increment()  
  327.         {  
  328.             incrementAndGet();  
  329.         }  
  330. void decrement()  
  331.         {  
  332.             getAndAdd(-1);  
  333.         }  
  334.         T getAndSet(T newValue)  
  335.         {  
  336. return __sync_lock_test_and_set(&value_, newValue);  
  337.         }  
  338. private:  
  339. volatile T value_;  
  340. };  
  341. typedef AtomicIntegerT<int32_t> AtomicInt32;  
  342. typedef AtomicIntegerT<int64_t> AtomicInt64;  
  343. class Channel;//前向声明,事件分发器主要用于事件注册与事件处理(事件回调)
  344. class Poller;//IO复用机制,主要功能是监听事件集合,即select,poll,epoll的功能
  345. class Timer;  
  346. class TimerId;  
  347. class Timestamp;  
  348. class TimerQueue;  
  349. class TcpConnection;  
  350. class Buffer;  
  351. typedef shared_ptr<TcpConnection> TcpConnectionPtr;  
  352. typedef function<void()> TimerCallback;  
  353. typedef function<void (const TcpConnectionPtr&)> ConnectionCallback;  
  354. typedef function<void (const TcpConnectionPtr&,Buffer* buf)> MessageCallback;  
  355. typedef function<void (const TcpConnectionPtr&)> WriteCompleteCallback;  
  356. typedef function<void (const TcpConnectionPtr&)> CloseCallback;  
  357. /*
  358. *EventLoop: 事件循环,一个线程一个事件循环即one loop per thread,其主要功能是运行事件循环如等待事件发生然后处理发生的事件
  359. */
  360. class EventLoop:noncopyable{  
  361. public:  
  362. //实现事件循环
  363. //实现定时回调功能,通过timerfd和TimerQueue实现
  364. //实现用户任务回调,为了线程安全有可能其它线程向IO线程的EventLoop添加任务,此时通过eventfd通知EventLoop执行用户任务
  365. typedef function<void()> Functor;//回调函数
  366.         EventLoop();  
  367.         ~EventLoop();  
  368. void loop();//EventLoop的主体,用于事件循环,Eventloop::loop()->Poller::Poll()获得就绪的事件集合并通过Channel::handleEvent()执行就绪事件回调
  369. void quit();//终止事件循环,通过设定标志位所以有一定延迟
  370. //Timestamp pollReturnTime() const;
  371. void assertInLoopThread(){//若运行线程不拥有EventLoop则退出,保证one loop per thread
  372. if(!isInLoopThread()){  
  373.                 abortNotInLoopThread();  
  374.             }  
  375.         }  
  376. bool isInLoopThread() const{return threadID_==syscall(SYS_gettid);}//判断运行线程是否为拥有此EventLoop的线程
  377.         TimerId runAt(const Timestamp& time,const TimerCallback& cb);//绝对时间执行定时器回调cb
  378.         TimerId runAfter(double delay,const TimerCallback& cb);//相对时间执行定时器回调
  379.         TimerId runEvery(double interval,const TimerCallback& cb);//每隔interval执行定时器回调
  380. void runInLoop(const Functor& cb);//用于IO线程执行用户回调(如EventLoop由于执行事件回调阻塞了,此时用户希望唤醒EventLoop执行用户指定的任务)
  381. void queueInLoop(const Functor& cb);//唤醒IO线程(拥有此EventLoop的线程)并将用户指定的任务回调放入队列
  382. void cancel(TimerId tiemrId);  
  383. void wakeup();//唤醒IO线程
  384. void updateChannel(Channel* channel);//更新事件分发器Channel,完成文件描述符fd向事件集合注册事件及事件回调函数
  385. void removeChannel(Channel* channel);  
  386. private:  
  387. void abortNotInLoopThread();//在不拥有EventLoop线程中终止
  388. void handleRead();//timerfd上可读事件回调
  389. void doPendingFunctors();//执行队列pendingFunctors中的用户任务回调
  390. typedef vector<Channel*> ChannelList;//事件分发器Channel容器,一个Channel只负责一个文件描述符fd的事件分发
  391. bool looping_;//事件循环主体loop是运行标志
  392. bool quit_;//取消循环主体标志
  393. const pid_t threadID_;//EventLoop的附属线程ID
  394.         scoped_ptr<Poller> poller_;//IO复用器Poller用于监听事件集合
  395. //scoped_ptr<Epoller> poller_;
  396.         ChannelList activeChannels_;//类似与poll的就绪事件集合,这里集合换成Channel(事件分发器具备就绪事件回调功能)
  397. //Timestamp pollReturnTime_;
  398. int wakeupFd_;//eventfd用于唤醒EventLoop所在线程
  399.         scoped_ptr<Channel> wakeupChannel_;//通过wakeupChannel_观察wakeupFd_上的可读事件,当可读时表明需要唤醒EventLoop所在线程执行用户回调
  400.         Mutex mutex_;//互斥量用以保护队列
  401.         vector<Functor> pendingFunctors_;//用户任务回调队列
  402.         scoped_ptr<TimerQueue> timerQueue_;//定时器队列用于存放定时器
  403. bool callingPendingFunctors_;//是否有用户任务回调标志
  404. };  
  405. /*
  406.  *Poller: IO Multiplexing Poller即poll的封装,主要完成事件集合的监听
  407.  */
  408. class Poller:noncopyable{//生命期和EventLoop一样长,不拥有Channel
  409. public:  
  410. typedef vector<Channel*> ChannelList;//Channel容器(Channel包含了文件描述符fd和fd注册的事件及事件回调函数),Channel包含文件描述符及其注册事件及其事件回调函数,这里主要用于返回就绪事件集合
  411.         Poller(EventLoop* loop);  
  412.         ~Poller();  
  413.         Timestamp Poll(int timeoutMs,ChannelList* activeChannels);//Poller的核心功能,通过poll系统调用将就绪事件集合通过activeChannels返回,并EventLoop::loop()->Channel::handelEvent()执行相应的就绪事件回调
  414. void updateChannel(Channel* channel);//Channel::update(this)->EventLoop::updateChannel(Channel*)->Poller::updateChannel(Channel*)负责维护和更新pollfs_和channels_,更新或添加Channel到Poller的pollfds_和channels_中(主要是文件描述符fd对应的Channel可能想修改已经向poll注册的事件或者fd想向poll注册事件)
  415. void assertInLoopThread(){//判定是否和EventLoop的隶属关系,EventLoop要拥有此Poller
  416.             ownerLoop_->assertInLoopThread();  
  417.         }  
  418. void removeChannel(Channel* channel);//通过EventLoop::removeChannel(Channel*)->Poller::removeChannle(Channel*)注销pollfds_和channels_中的Channel
  419. private:  
  420. void fillActiveChannels(int numEvents,ChannelList* activeChannels) const;//遍历pollfds_找出就绪事件的fd填入activeChannls,这里不能一边遍历pollfds_一边执行Channel::handleEvent()因为后者可能添加或者删除Poller中含Channel的pollfds_和channels_(遍历容器的同时存在容器可能被修改是危险的),所以Poller仅仅是负责IO复用,不负责事件分发(交给Channel处理)
  421. typedef vector<struct pollfd> PollFdList;//struct pollfd是poll系统调用监听的事件集合参数
  422. typedef map<int,Channel*> ChannelMap;//文件描述符fd到IO分发器Channel的映射,通过fd可以快速找到Channel
  423. //注意:Channel中有fd成员可以完成Channel映射到fd的功能,所以fd和Channel可以完成双射
  424.         EventLoop* ownerLoop_;//隶属的EventLoop
  425.         PollFdList pollfds_;//监听事件集合
  426.         ChannelMap channels_;//文件描述符fd到Channel的映射
  427. };  
  428. /*
  429.  *Channel: 事件分发器,该类包含:文件描述符fd、fd欲监听的事件、事件的处理函数(事件回调函数)
  430.  */
  431. class Channel:noncopyable{  
  432. public:  
  433. typedef function<void()> EventCallback;//事件回调函数类型,回调函数的参数为空,这里将参数类型已经写死了
  434. typedef function<void()> ReadEventCallback;  
  435.         Channel(EventLoop* loop,int fd);//一个Channel只负责一个文件描述符fd但Channel不拥有fd,可见结构应该是这样的:EventLoop调用Poller监听事件集合,就绪的事件集合元素就是Channel。但Channel的功能不仅是返回就绪事件,还具备事件处理功能
  436.         ~Channel();//目前缺失一个功能:~Channel()->EventLoop::removeChannel()->Poller::removeChannel()注销Poller::map<int,Channel*>的Channel*避免空悬指针
  437. void handleEvent();//这是Channel的核心,当fd对应的事件就绪后Channel::handleEvent()执行相应的事件回调,如可读事件执行readCallback_()
  438. void setReadCallback(const ReadEventCallback& cb){//可读事件回调
  439.             readCallback_=cb;  
  440.         }  
  441. void setWriteCallback(const EventCallback& cb){//可写事件回调
  442.             writeCallback_=cb;  
  443.         }  
  444. void setErrorCallback(const EventCallback& cb){//出错事件回调
  445.             errorCallback_=cb;  
  446.         }  
  447. void setCloseCallback(const EventCallback& cb){  
  448.             closeCallback_=cb;  
  449.         }  
  450. int fd() const{return fd_;}//返回Channel负责的文件描述符fd,即建立Channel到fd的映射
  451. int events() const{return events_;}//返回fd域注册的事件类型
  452. void set_revents(int revt){//设定fd的就绪事件类型,再poll返回就绪事件后将就绪事件类型传给此函数,然后此函数传给handleEvent,handleEvent根据就绪事件的类型决定执行哪个事件回调函数
  453.             revents_=revt;  
  454.         }  
  455. bool isNoneEvent() const{//fd没有想要注册的事件
  456. return events_==kNoneEvent;  
  457.         }  
  458. void enableReading(){//fd注册可读事件
  459.             events_|=kReadEvent;  
  460.             update();  
  461.         }  
  462. void enableWriting(){//fd注册可写事件
  463.             events_|=kWriteEvent;  
  464.             update();  
  465.         }  
  466. void disableWriting(){  
  467.             events_&=~kWriteEvent;  
  468.             update();  
  469.         }  
  470. void disableAll(){events_=kReadEvent;update();}  
  471. bool isWriting() const{  
  472. return events_&kWriteEvent;  
  473.         }  
  474. int index(){return index_;}//index_是本Channel负责的fd在poll监听事件集合的下标,用于快速索引到fd的pollfd
  475. void set_index(int idx){index_=idx;}  
  476.         EventLoop* ownerLoop(){return loop_;}  
  477. private:  
  478. void update();//Channel::update(this)->EventLoop::updateChannel(Channel*)->Poller::updateChannel(Channel*)最后Poller修改Channel,若Channel已经存在于Poller的vector<pollfd> pollfds_(其中Channel::index_是vector的下标)则表明Channel要重新注册事件,Poller调用Channel::events()获得事件并重置vector中的pollfd;若Channel没有在vector中则向Poller的vector添加新的文件描述符事件到事件表中,并将vector.size(),(vector每次最后追加),给Channel::set_index()作为Channel记住自己在Poller中的位置
  479. static const int kNoneEvent;//无任何事件
  480. static const int kReadEvent;//可读事件
  481. static const int kWriteEvent;//可写事件
  482. bool eventHandling_;  
  483.         EventLoop* loop_;//Channel隶属的EventLoop(原则上EventLoop,Poller,Channel都是一个IO线程)
  484. const int fd_;//每个Channel唯一负责的文件描述符,Channel不拥有fd
  485. int events_;//fd_注册的事件
  486. int revents_;//通过poll返回的就绪事件类型
  487. int index_;//在poll的监听事件集合pollfd的下标,用于快速索引到fd的pollfd
  488.         ReadEventCallback readCallback_;//可读事件回调函数,当poll返回fd_的可读事件时调用此函数执行相应的事件处理,该函数由用户指定
  489.         EventCallback writeCallback_;//可写事件回调函数
  490.         EventCallback errorCallback_;//出错事件回调函数
  491.         EventCallback closeCallback_;  
  492. };  
  493. /*
  494. *时间戳,采用一个整数表示微秒数
  495. */
  496. class Timestamp{  
  497. public:  
  498.         Timestamp():microSecondsSinceEpoch_(0){}  
  499. explicit Timestamp(int64_t microseconds):microSecondsSinceEpoch_(microseconds){}  
  500. void swap(Timestamp& that){  
  501.             std::swap(microSecondsSinceEpoch_,that.microSecondsSinceEpoch_);  
  502.         }  
  503. bool valid() const{return microSecondsSinceEpoch_>0;}  
  504.         int64_t microSecondsSinceEpoch() const {return microSecondsSinceEpoch_;}  
  505. static Timestamp now(){  
  506. struct timeval tv;  
  507.             gettimeofday(&tv, NULL);  
  508.             int64_t seconds = tv.tv_sec;  
  509. return Timestamp(seconds * kMicroSecondsPerSecond + tv.tv_usec);  
  510.         }  
  511. static Timestamp invalid(){return Timestamp();}  
  512. static const int kMicroSecondsPerSecond=1000*1000;  
  513. private:  
  514.         int64_t microSecondsSinceEpoch_;  
  515. };  
  516. //时间戳的比较
  517. inline bool operator<(Timestamp lhs, Timestamp rhs)  
  518. {  
  519. return lhs.microSecondsSinceEpoch() < rhs.microSecondsSinceEpoch();  
  520. }  
  521. inline bool operator==(Timestamp lhs, Timestamp rhs)  
  522. {  
  523. return lhs.microSecondsSinceEpoch() == rhs.microSecondsSinceEpoch();  
  524. }  
  525. inline double timeDifference(Timestamp high, Timestamp low)  
  526. {  
  527.   int64_t diff = high.microSecondsSinceEpoch() - low.microSecondsSinceEpoch();  
  528. return static_cast<double>(diff) / Timestamp::kMicroSecondsPerSecond;  
  529. }  
  530. inline Timestamp addTime(Timestamp timestamp, double seconds)  
  531. {  
  532.   int64_t delta = static_cast<int64_t>(seconds * Timestamp::kMicroSecondsPerSecond);  
  533. return Timestamp(timestamp.microSecondsSinceEpoch() + delta);  
  534. }  
  535. /*
  536.  * TimerId带有唯一序号的Timer
  537.  */
  538. class TimerId{  
  539. public:  
  540.         TimerId(Timer* timer=NULL,int64_t seq=0)  
  541.             :timer_(timer),sequence_(seq){}  
  542. friend class TimerQueue;  
  543. private:  
  544.         Timer* timer_;  
  545.         int64_t sequence_;  
  546. };  
  547. /*
  548.  *定时器
  549.  */
  550. class Timer : boost::noncopyable  
  551. {  
  552. public:  
  553. typedef function<void()> TimerCallback;//定时器回调函数
  554. //typedef function<void()> callback;
  555.         Timer(const TimerCallback& cb, Timestamp when, double interval)  
  556.             :callback_(cb),expiration_(when),  
  557.             interval_(interval),repeat_(interval > 0.0),  
  558.             sequence_(s_numCreated_.incrementAndGet()){}  
  559. void run() const {//执行定时器回调
  560.             callback_();  
  561.         }  
  562.         Timestamp expiration() const  { return expiration_; }//返回定时器的超时时间戳
  563. bool repeat() const { return repeat_; }//是否周期性定时
  564.         int64_t sequence() const{return sequence_;}  
  565. void restart(Timestamp now);//重置定时器
  566. private:  
  567. const TimerCallback callback_;//超时回调函数
  568.         Timestamp expiration_;//超时时间戳
  569. const double interval_;//相对时间,作为参数传给时间戳生成具体的超时时间
  570. const bool repeat_;//是否重复定时标志
  571. const int64_t sequence_;//
  572. static AtomicInt64 s_numCreated_;//原子操作,用于生成定时器ID
  573. };  
  574. AtomicInt64 Timer::s_numCreated_;  
  575. void Timer::restart(Timestamp now){  
  576. if (repeat_){//周期定时
  577.         expiration_ = addTime(now, interval_);  
  578.     }  
  579. else{  
  580.         expiration_ = Timestamp::invalid();  
  581.     }  
  582. }  
  583. /*
  584.  * timerfd的相关操作,可用于TimerQueue实现超时器管理
  585.  */
  586. int createTimerfd(){//创建timerfd
  587. int timerfd = ::timerfd_create(CLOCK_MONOTONIC,TFD_NONBLOCK | TFD_CLOEXEC);  
  588. if (timerfd < 0){  
  589.         printf("Timderfd::create() error\n");  
  590.     }  
  591. return timerfd;  
  592. }  
  593. struct timespec howMuchTimeFromNow(Timestamp when){  
  594.     int64_t microseconds = when.microSecondsSinceEpoch()- Timestamp::now().microSecondsSinceEpoch();  
  595. if (microseconds < 100){  
  596.         microseconds = 100;  
  597.     }  
  598. struct timespec ts;  
  599.     ts.tv_sec = static_cast<time_t>(microseconds / Timestamp::kMicroSecondsPerSecond);  
  600.     ts.tv_nsec = static_cast<long>((microseconds % Timestamp::kMicroSecondsPerSecond) * 1000);  
  601. return ts;  
  602. }  
  603. void readTimerfd(int timerfd, Timestamp now){//timerfd的可读事件回调
  604.     uint64_t howmany;  
  605.     ssize_t n = ::read(timerfd, &howmany, sizeof howmany);  
  606. if (n != sizeof howmany){  
  607.         printf("readTimerfd error\n");  
  608.     }  
  609. }  
  610. void resetTimerfd(int timerfd, Timestamp expiration)//重置timerfd的计时
  611. {  
  612. struct itimerspec newValue;  
  613. struct itimerspec oldValue;  
  614.     bzero(&newValue, sizeof newValue);  
  615.     bzero(&oldValue, sizeof oldValue);  
  616.     newValue.it_value = howMuchTimeFromNow(expiration);  
  617. int ret = ::timerfd_settime(timerfd, 0, &newValue, &oldValue);  
  618. if (ret){  
  619.         printf("timerfd_settime erro\n");  
  620.     }  
  621. }  
  622. /*
  623.  *定时器队列
  624.  */
  625. class TimerQueue : boost::noncopyable  
  626. {//其通过添加一个timerfd到EventLoop中,当timerfd可读事件就绪时,TimerQueue::handleRead()遍历容器内的超时的定时器并执行这些超时定时器的回调
  627. //定时器容器为set<pair<Timestamp,Timer*> >,采用pair作为key的原因是可能在一个时刻有多个相同的Timestamp时间戳
  628. //当向定时器容器set添加定时器timer的时候会检查当前最小的定时器,并将最小的定时时间付赋给timerfd
  629. public:  
  630. typedef function<void()> TimerCallback;//定时器回调
  631.         TimerQueue(EventLoop* loop);  
  632.         ~TimerQueue();  
  633.         TimerId addTimer(const TimerCallback& cb,Timestamp when,double interval);//添加定时器到定时器队列中
  634. void cancel(TimerId timerId);  
  635. private:  
  636. typedef pair<Timestamp, Timer*> Entry;//采用此作为键值
  637. typedef set<Entry> TimerList;//set只有key无value且有序
  638. typedef pair<Timer*,int64_t> ActiveTimer;  
  639. typedef set<ActiveTimer> ActiveTimerSet;  
  640. void handleRead();//timerfd的可读回调
  641. void addTimerInLoop(Timer* timer);//添加定时器
  642. void cancelInLoop(TimerId timerId);  
  643.         std::vector<Entry> getExpired(Timestamp now);//获取所有超时的定时器
  644. void reset(const std::vector<Entry>& expired, Timestamp now);//超时的定时器是否需要重新定时
  645. bool insert(Timer* timer);//插入定时器到队列中
  646.         EventLoop* loop_;//TimerQueue所属的EventLoop
  647. const int timerfd_;//定时器队列本身需要在定时器超时后执行队列中所有超时定时器的回调
  648.         Channel timerfdChannel_;//采用timerfdChannel_观察timerfd_的可读事件啊,当timerfd_可读表明定时器队列中有定时器超时
  649.         TimerList timers_;//定时器队列
  650. bool callingExpiredTimers_;  
  651.         ActiveTimerSet activeTimers_;  
  652.         ActiveTimerSet cancelingTimers_;  
  653. };  
  654. /*
  655.  * TimerQueue实现
  656.  */
  657. TimerQueue::TimerQueue(EventLoop* loop)  
  658.     :loop_(loop),timerfd_(createTimerfd()),  
  659.     timerfdChannel_(loop, timerfd_),timers_(),  
  660.     callingExpiredTimers_(false)  
  661. {  
  662.     timerfdChannel_.setReadCallback(bind(&TimerQueue::handleRead, this));  
  663.     timerfdChannel_.enableReading();//timerfd注册可读事件
  664. }  
  665. TimerQueue::~TimerQueue(){  
  666.     ::close(timerfd_);  
  667. for (TimerList::iterator it = timers_.begin();it != timers_.end(); ++it)  
  668.     {  
  669. delete it->second;  
  670.     }  
  671. }  
  672. TimerId TimerQueue::addTimer(const TimerCallback& cb,Timestamp when,double interval)//其它线程向IO线程添加用户回调时将添加操作转移到IO线程中去,从而保证线程安全one loop per thread
  673. {//由EventLoop::runAt等函数调用
  674.     Timer* timer = new Timer(cb, when, interval);  
  675.     loop_->runInLoop(bind(&TimerQueue::addTimerInLoop,this,timer));//通过EventLoop::runInLoop()->TimerQueue::queueInLoop()
  676. //runInLoop语义是若是本IO线程想要添加定时器则直接由addTimerInLoop添加,若是其它线程向IO线程添加定时器则需要间接通过queueInLoop添加
  677. return TimerId(timer,timer->sequence());  
  678. }  
  679. void TimerQueue::addTimerInLoop(Timer* timer){//IO线程自己向自己添加定时器
  680.     loop_->assertInLoopThread();  
  681. bool earliestChanged=insert(timer);//若当前插入的定时器比队列中的定时器都早则返回真
  682. if(earliestChanged){  
  683.         resetTimerfd(timerfd_,timer->expiration());//timerfd重新设置超时时间
  684.     }  
  685. }  
  686. void TimerQueue::cancel(TimerId timerId){  
  687.     loop_->runInLoop(bind(&TimerQueue::cancelInLoop,this,timerId));  
  688. }  
  689. void TimerQueue::cancelInLoop(TimerId timerId){  
  690.     loop_->assertInLoopThread();  
  691.     assert(timers_.size()==activeTimers_.size());  
  692.     ActiveTimer timer(timerId.timer_,timerId.sequence_);  
  693.     ActiveTimerSet::iterator it=activeTimers_.find(timer);  
  694. if(it!=activeTimers_.end()){  
  695. size_t n=timers_.erase(Entry(it->first->expiration(),it->first));  
  696.         assert(n==1);  
  697.         (void)n;  
  698. delete it->first;  
  699.         activeTimers_.erase(it);  
  700.     }  
  701. else if(callingExpiredTimers_){  
  702.         cancelingTimers_.insert(timer);  
  703.     }  
  704.     assert(timers_.size()==activeTimers_.size());  
  705. }  
  706. void TimerQueue::handleRead(){//timerfd的回调函数
  707.     loop_->assertInLoopThread();  
  708.     Timestamp now(Timestamp::now());  
  709.     readTimerfd(timerfd_, now);  
  710.     std::vector<Entry> expired = getExpired(now);//TimerQueue::timerfd可读表明队列中有定时器超时,则需要找出那些超时的定时器
  711.     callingExpiredTimers_=true;  
  712.     cancelingTimers_.clear();  
  713. for (std::vector<Entry>::iterator it = expired.begin();it!= expired.end(); ++it)//
  714.     {  
  715.         it->second->run();//执行定时器Timer的超时回调
  716.     }  
  717.     callingExpiredTimers_=false;  
  718.     reset(expired, now);//查看已经执行完的超市定时器是否需要再次定时
  719. }  
  720. std::vector<TimerQueue::Entry> TimerQueue::getExpired(Timestamp now)//获取队列中的超时的定时器(可能多个)
  721. {  
  722.     assert(timers_.size()==activeTimers_.size());  
  723.     std::vector<Entry> expired;  
  724.     Entry sentry = std::make_pair(now, reinterpret_cast<Timer*>(UINTPTR_MAX));  
  725.     TimerList::iterator it = timers_.lower_bound(sentry);//返回比参数小的下界,即返回第一个当前未超时的定时器(可能没有这样的定时器)
  726. //lower_bound(value_type& val)调用key_comp返回第一个不小于val的迭代器
  727.     assert(it == timers_.end() || now < it->first);  
  728.     std::copy(timers_.begin(), it, back_inserter(expired));  
  729.     timers_.erase(timers_.begin(), it);  
  730.     BOOST_FOREACH(Entry entry,expired){  
  731.         ActiveTimer timer(entry.second,entry.second->sequence());  
  732. size_t n=activeTimers_.erase(timer);  
  733.         assert(n==1);  
  734.         (void)n;  
  735.     }  
  736. return expired;//返回已经超时的那部分定时器
  737. }  
  738. void TimerQueue::reset(const std::vector<Entry>& expired, Timestamp now)//已经执行完超时回调的定时器是否需要重置定时
  739. {  
  740.     Timestamp nextExpire;  
  741. for (std::vector<Entry>::const_iterator it = expired.begin();it != expired.end(); ++it)  
  742.     {  
  743.         ActiveTimer timer(it->second,it->second->sequence());  
  744. if (it->second->repeat()&&  
  745.                 cancelingTimers_.find(timer)==cancelingTimers_.end()){//需要再次定时
  746.             it->second->restart(now);  
  747.             insert(it->second);  
  748.         }  
  749. else{//否则删除该定时器
  750. delete it->second;  
  751.         }  
  752.     }  
  753. if (!timers_.empty()){//为超时定时器重新定时后需要获取当前最小的超时时间给timerfd,以防重置的这些超市定时器中含有最小的超时时间
  754.         nextExpire = timers_.begin()->second->expiration();  
  755.     }  
  756. if (nextExpire.valid()){  
  757.         resetTimerfd(timerfd_, nextExpire);//重置timerfd的超时时间
  758.     }  
  759. }  
  760. bool TimerQueue::insert(Timer* timer)//向超时队列中插入定时器
  761. {  
  762.     loop_->assertInLoopThread();  
  763.     assert(timers_.size()==activeTimers_.size());  
  764. bool earliestChanged = false;  
  765.     Timestamp when = timer->expiration();  
  766.     TimerList::iterator it = timers_.begin();  
  767. if (it == timers_.end() || when < it->first)  
  768.     {  
  769.         earliestChanged = true;//当前插入的定时器是队列中最小的定时器,此时外层函数需要重置timerfd的超时时间
  770.     }  
  771.     {  
  772.         pair<TimerList::iterator,bool> result=  
  773.             timers_.insert(Entry(when,timer));  
  774.         assert(result.second);  
  775.         (void)result;  
  776.     }  
  777.     {  
  778.         pair<ActiveTimerSet::iterator,bool> result=  
  779.             activeTimers_.insert(ActiveTimer(timer,timer->sequence()));  
  780.         assert(result.second);  
  781.         (void)result;  
  782.     }  
  783.     assert(timers_.size()==activeTimers_.size());  
  784. return earliestChanged;  
  785. }  
  786. /*
  787. *EventLoop成员实现
  788. */
  789. class IngnoreSigPipe{  
  790. public:  
  791.         IngnoreSigPipe(){  
  792.             ::signal(SIGPIPE,SIG_IGN);  
  793.         }  
  794. };  
  795. IngnoreSigPipe initObj;  
  796. __thread EventLoop* t_loopInThisThread=0;//线程私有数据表示线程是否拥有EventLoop
  797. const int kPollTimeMs=10000;//poll等待时间
  798. static int createEventfd(){//创建eventfd,eventfd用于唤醒
  799. int evtfd=eventfd(0,EFD_NONBLOCK|EFD_CLOEXEC);  
  800. if(evtfd<0){  
  801.         printf("Failed in eventfd\n");  
  802.         abort();  
  803.     }  
  804. return evtfd;  
  805. }  
  806. EventLoop::EventLoop()  
  807.     :looping_(false),  
  808.     quit_(false),  
  809.     threadID_(syscall(SYS_gettid)),  
  810.     poller_(new Poller(this)),  
  811.     timerQueue_(new TimerQueue(this)),//EventLoop用于一个定时器队列
  812.     wakeupFd_(createEventfd()),  
  813.     wakeupChannel_(new Channel(this,wakeupFd_)),//通过Channel观察wakeupFd_
  814.     callingPendingFunctors_(false)  
  815. {  
  816. if(!t_loopInThisThread){  
  817.         t_loopInThisThread=this;//EventLoop构造时线程私有数据记录
  818.     }  
  819.     wakeupChannel_->setReadCallback(bind(&EventLoop::handleRead,this));//设置eventfd的回调
  820.     wakeupChannel_->enableReading();//eventfd的可读事件,并Channel::update(this)将eventfd添加到poll事件表中
  821. }  
  822. EventLoop::~EventLoop(){  
  823.     assert(!looping_);  
  824.     close(wakeupFd_);  
  825.     t_loopInThisThread=NULL;//EventLoop析构将其置空
  826. }  
  827. void EventLoop::loop(){//EventLoop主循环,主要功能是监听事件集合,执行就绪事件的处理函数
  828.     assert(!looping_);  
  829.     assertInLoopThread();  
  830.     looping_=true;  
  831.     quit_=false;  
  832. while(!quit_){  
  833.         activeChannels_.clear();  
  834.         poller_->Poll(kPollTimeMs,&activeChannels_);//activeChannels是就绪事件
  835. for(ChannelList::iterator it=activeChannels_.begin();it!=activeChannels_.end();it++){  
  836.             (*it)->handleEvent();//处理就绪事件的回调函数,处理事件回调
  837.         }  
  838.         doPendingFunctors();//处理用户任务回调
  839.     }  
  840.     looping_=false;  
  841. }  
  842. void EventLoop::quit(){  
  843.     quit_=true;//停止主循环标志,主循环不会马上停止有延迟
  844. if(!isInLoopThread()){  
  845.         wakeup();//其它线程唤醒EventLoop线程且终止它
  846.     }  
  847. }  
  848. void EventLoop::updateChannel(Channel* channel){//主要用于文件描述符添加到poll的监听事件集合中
  849.     assert(channel->ownerLoop()==this);  
  850.     assertInLoopThread();  
  851.     poller_->updateChannel(channel);  
  852. }  
  853. void EventLoop::abortNotInLoopThread(){  
  854.     printf("abort not in Loop Thread\n");  
  855.     abort();//非本线程调用强行终止
  856. }  
  857. TimerId EventLoop::runAt(const Timestamp& time, const TimerCallback& cb)//绝对时间执行回调
  858. {  
  859. return timerQueue_->addTimer(cb, time, 0.0);  
  860. }  
  861. TimerId EventLoop::runAfter(double delay, const TimerCallback& cb)//相对时间执行回调
  862. {  
  863.     Timestamp time(addTime(Timestamp::now(), delay));  
  864. return runAt(time, cb);  
  865. }  
  866. TimerId EventLoop::runEvery(double interval, const TimerCallback& cb)//周期性回调
  867. {  
  868.     Timestamp time(addTime(Timestamp::now(), interval));//Timestamp::addTime
  869. return timerQueue_->addTimer(cb, time, interval);  
  870. }  
  871. void EventLoop::cancel(TimerId timerId){  
  872. return timerQueue_->cancel(timerId);  
  873. }  
  874. void EventLoop::runInLoop(const Functor& cb){  
  875. if(isInLoopThread()){//本IO线程调用则直接执行执行用户回调
  876.        cb();  
  877.     }  
  878. else{//其它线程调用runInLoop则向用户回调队列添加,保证线程安全one loop per thread
  879.         queueInLoop(cb);  
  880.     }  
  881. }  
  882. void EventLoop::queueInLoop(const Functor& cb){  
  883.     {  
  884.         MutexLockGuard lock(mutex_);//互斥量保护用户回调队列
  885.         pendingFunctors_.push_back(cb);  
  886.     }  
  887. if(!isInLoopThread()||callingPendingFunctors_){  
  888.         wakeup();//其它线程添加用户回调任务或者EventLoop的IO线程正在处理用户任务回调时,若阻塞则唤醒IO线程
  889.     }  
  890. }  
  891. void EventLoop::handleRead(){//eventfd可读回调
  892.     uint64_t one=1;  
  893.     ssize_t n=read(wakeupFd_,&one,sizeof(one));  
  894. if(n!=sizeof(one)){  
  895.         printf("EventLoop::handleRead() error\n");  
  896.     }  
  897. }  
  898. void EventLoop::doPendingFunctors(){//执行用户任务回调
  899.     vector<Functor> functors;  
  900.     callingPendingFunctors_=true;  
  901.     {  
  902.         MutexLockGuard lock(mutex_);  
  903.         functors.swap(pendingFunctors_);//采用swap而不是在这里执行回调是为了缩小临界区
  904.     }  
  905. for(size_t i=0;i<functors.size();i++){  
  906.         functors[i]();  
  907.     }  
  908.     callingPendingFunctors_=false;  
  909. }  
  910. void EventLoop::wakeup(){  
  911.     uint64_t one=1;  
  912.     ssize_t n=write(wakeupFd_,&one,sizeof(one));//通过eventfd通知
  913. if(n!=sizeof(one)){  
  914.         printf("EventLoop::wakeup() write error\n");  
  915.     }  
  916. }  
  917. void EventLoop::removeChannel(Channel* channel){  
  918.     assert(channel->ownerLoop()==this);  
  919.     assertInLoopThread();  
  920.     poller_->removeChannel(channel);  
  921. }  
  922. /*
  923. *Poller成员实现
  924. */
  925. Poller::Poller(EventLoop* loop):ownerLoop_(loop){}//Poller明确所属的EventLoop
  926. Poller::~Poller(){}  
  927. Timestamp Poller::Poll(int timeoutMs,ChannelList* activeChannels){  
  928. int numEvents=poll(&*pollfds_.begin(),pollfds_.size(),timeoutMs);//poll监听事件集合pollfds_
  929.     Timestamp now(Timestamp::now());  
  930. if(numEvents>0){  
  931.         fillActiveChannels(numEvents,activeChannels);//将就绪的事件添加到activeChannels
  932.     }  
  933. else if(numEvents==0){  
  934.     }  
  935. else{  
  936.         printf("Poller::Poll error\n");  
  937.     }  
  938. return now;  
  939. }  
  940. void Poller::fillActiveChannels(int numEvents,ChannelList* activeChannels) const{//将就绪事件通过activeChannels返回
  941. for(PollFdList::const_iterator pfd=pollfds_.begin();pfd!=pollfds_.end()&&numEvents>0;++pfd){  
  942. if(pfd->revents>0){  
  943.             --numEvents;//若numEvents个事件全部找到就不需要再遍历容器剩下的部分
  944.             ChannelMap::const_iterator ch=channels_.find(pfd->fd);  
  945.             assert(ch!=channels_.end());  
  946.             Channel* channel=ch->second;  
  947.             assert(channel->fd()==pfd->fd);  
  948.             channel->set_revents(pfd->revents);  
  949.             activeChannels->push_back(channel);  
  950.         }  
  951.     }  
  952. }  
  953. void Poller::updateChannel(Channel* channel){  
  954.     assertInLoopThread();  
  955. if(channel->index()<0){//若channel的文件描述符fd没有添加到poll的监听事件集合中
  956.         assert(channels_.find(channel->fd())==channels_.end());  
  957. struct pollfd pfd;  
  958.         pfd.fd=channel->fd();  
  959.         pfd.events=static_cast<short>(channel->events());  
  960.         pfd.revents=0;  
  961.         pollfds_.push_back(pfd);  
  962. int idx=static_cast<int>(pollfds_.size())-1;  
  963.         channel->set_index(idx);  
  964.         channels_[pfd.fd]=channel;  
  965.     }  
  966. else{//若已经添加到监听事件集合中,但是需要修改
  967.         assert(channels_.find(channel->fd())!=channels_.end());  
  968.         assert(channels_[channel->fd()]==channel);  
  969. int idx=channel->index();  
  970.         assert(0<=idx&&idx<static_cast<int>(pollfds_.size()));  
  971. struct pollfd& pfd=pollfds_[idx];  
  972.         assert(pfd.fd==channel->fd()||pfd.fd==-channel->fd()-1);//pfd.fd=-channel->fd()-1是为了让poll忽略那些kNoneEvent的描述符,-1是因为:fd可能为0所以-channel->fd()可能还是0,不能区分一个不可能的描述符
  973.         pfd.events=static_cast<short>(channel->events());//修改注册事件类型
  974.         pfd.revents=0;  
  975. if(channel->isNoneEvent()){  
  976.             pfd.fd=-channel->fd()-1;//channel::events_=kNoneEvent时poll忽略那些不可能的描述符-channel->fd()-1,-1原因见上面
  977.         }  
  978.     }  
  979. }  
  980. void Poller::removeChannel(Channel* channel)  
  981. {  
  982.   assertInLoopThread();  
  983.   assert(channels_.find(channel->fd()) != channels_.end());  
  984.   assert(channels_[channel->fd()] == channel);  
  985.   assert(channel->isNoneEvent());  
  986. int idx = channel->index();  
  987.   assert(0 <= idx && idx < static_cast<int>(pollfds_.size()));  
  988. const struct pollfd& pfd = pollfds_[idx]; (void)pfd;  
  989.   assert(pfd.fd == -channel->fd()-1 && pfd.events == channel->events());  
  990. size_t n = channels_.erase(channel->fd());  
  991.   assert(n == 1); (void)n;  
  992. if (implicit_cast<size_t>(idx) == pollfds_.size()-1) {  
  993.     pollfds_.pop_back();  
  994.   } else {  
  995. int channelAtEnd = pollfds_.back().fd;  
  996.     iter_swap(pollfds_.begin()+idx, pollfds_.end()-1);  
  997. if (channelAtEnd < 0) {  
  998.       channelAtEnd = -channelAtEnd-1;  
  999.     }  
  1000.     channels_[channelAtEnd]->set_index(idx);  
  1001.     pollfds_.pop_back();  
  1002.   }  
  1003. }  
  1004. /*
  1005. *Channel成员实现
  1006. */
  1007. const int Channel::kNoneEvent=0;//无事件
  1008. const int Channel::kReadEvent=POLLIN|POLLPRI;//可读事件
  1009. const int Channel::kWriteEvent=POLLOUT;//可写事件
  1010. Channel::Channel(EventLoop* loop,int fdArg)  
  1011.     :loop_(loop),fd_(fdArg),events_(0),revents_(0),  
  1012.     index_(-1),eventHandling_(false)  
  1013.     {}  
  1014. void Channel::update(){//添加或修改文件描述符的事件类型
  1015.     loop_->updateChannel(this);  
  1016. }  
  1017. Channel::~Channel(){  
  1018.     assert(!eventHandling_);  
  1019. }  
  1020. void Channel::handleEvent(){//处理就绪事件的处理函数
  1021.     eventHandling_=true;  
  1022. if(revents_&POLLNVAL){  
  1023.         printf("Channel::handleEvent() POLLNVAL\n");  
  1024.     }  
  1025. if((revents_&POLLHUP)&&!(revents_&POLLIN)){//出错回调
  1026.         printf("Channel::handle_event() POLLUP\n");  
  1027. if(closeCallback_)  
  1028.             closeCallback_();  
  1029.     }  
  1030. if(revents_&(POLLERR|POLLNVAL)){//可读回调
  1031. if(errorCallback_)  
  1032.             errorCallback_();  
  1033.     }  
  1034. if(revents_&(POLLIN|POLLPRI|POLLRDHUP)){  
  1035. if(readCallback_) readCallback_();  
  1036.     }  
  1037. if(revents_&POLLOUT){//可写回调
  1038. if(writeCallback_)  
  1039.             writeCallback_();  
  1040.     }  
  1041.     eventHandling_=false;  
  1042. }  
  1043. /*
  1044. *开启一个线程执行一个EventLoop,这才是one loop per thread
  1045. */
  1046. class EventLoopThread:noncopyable{  
  1047. public:  
  1048.         EventLoopThread()  
  1049.             :loop_(NULL),exiting_(false),  
  1050.             thread_(bind(&EventLoopThread::threadFunc,this)),  
  1051.             mutex_(),cond_(mutex_){}  
  1052.         ~EventLoopThread(){  
  1053.             exiting_=true;  
  1054.             loop_->quit();  
  1055.             thread_.join();  
  1056.         }  
  1057.         EventLoop* startLoop(){  
  1058. //assert(!thread_.started());
  1059.             thread_.start();  
  1060.             {  
  1061.                 MutexLockGuard lock(mutex_);  
  1062. while(loop_==NULL){  
  1063.                     cond_.wait();  
  1064.                 }  
  1065.             }  
  1066. return loop_;  
  1067.         }  
  1068. private:  
  1069. void threadFunc(){  
  1070.             EventLoop loop;  
  1071.             {  
  1072.                 MutexLockGuard lock(mutex_);  
  1073.                 loop_=&loop;  
  1074.                 cond_.notify();  
  1075.             }  
  1076.             loop.loop();  
  1077.         }  
  1078.         EventLoop* loop_;  
  1079. bool exiting_;  
  1080.         Thread thread_;  
  1081.         Mutex mutex_;  
  1082.         Condition cond_;  
  1083. };  
  1084. /*
  1085.  * EventLoopThreadPool
  1086.  */
  1087. class EventLoopThreadPool:noncopyable{  
  1088. public:  
  1089.         EventLoopThreadPool(EventLoop* baseLoop)  
  1090.             :baseLoop_(baseLoop),  
  1091.             started_(false),numThreads_(0),next_(0){}  
  1092.         ~EventLoopThreadPool(){}  
  1093. void setThreadNum(int numThreads){numThreads_=numThreads;}  
  1094. void start(){  
  1095.             assert(!started_);  
  1096.             baseLoop_->assertInLoopThread();  
  1097.             started_=true;  
  1098. for(int i=0;i<numThreads_;i++){  
  1099.                 EventLoopThread* t=new EventLoopThread;  
  1100.                 threads_.push_back(t);  
  1101.                 loops_.push_back(t->startLoop());  
  1102.             }  
  1103.         }  
  1104.         EventLoop* getNextLoop(){  
  1105.             baseLoop_->assertInLoopThread();  
  1106.             EventLoop* loop=baseLoop_;  
  1107. if(!loops_.empty()){  
  1108.                 loop=loops_[next_];  
  1109.                 ++next_;  
  1110. if(static_cast<size_t>(next_)>=loops_.size())  
  1111.                     next_=0;  
  1112.             }  
  1113. return loop;  
  1114.         }  
  1115. private:  
  1116.         EventLoop* baseLoop_;  
  1117. bool started_;  
  1118. int numThreads_;  
  1119. int next_;  
  1120.         ptr_vector<EventLoopThread> threads_;  
  1121.         vector<EventLoop*> loops_;  
  1122. };  
  1123. /*
  1124.  *常用的socket选项
  1125.  */
  1126. namespace sockets{  
  1127. inline uint64_t hostToNetwork64(uint64_t host64)  
  1128. {//主机字节序转为网络字节序
  1129. return htobe64(host64);  
  1130. }  
  1131. inline uint32_t hostToNetwork32(uint32_t host32)  
  1132. {  
  1133. return htonl(host32);  
  1134. }  
  1135. inline uint16_t hostToNetwork16(uint16_t host16)  
  1136. {  
  1137. return htons(host16);  
  1138. }  
  1139. inline uint64_t networkToHost64(uint64_t net64)  
  1140. {//网络字节序转为主机字节序
  1141. return be64toh(net64);  
  1142. }  
  1143. inline uint32_t networkToHost32(uint32_t net32)  
  1144. {  
  1145. return ntohl(net32);  
  1146. }  
  1147. inline uint16_t networkToHost16(uint16_t net16)  
  1148. {  
  1149. return ntohs(net16);  
  1150. }  
  1151. typedef struct sockaddr SA;  
  1152. const SA* sockaddr_cast(const struct sockaddr_in* addr){//强制转换
  1153. return static_cast<const SA*>(implicit_cast<const void*>(addr));  
  1154. }  
  1155. SA* sockaddr_cast(struct sockaddr_in* addr){  
  1156. return static_cast<SA*>(implicit_cast<void*>(addr));  
  1157. }  
  1158. void setNonBlockAndCloseOnExec(int sockfd){//将描述符设置为非阻塞和O_CLOEXEC(close on exec)
  1159. int flags = ::fcntl(sockfd, F_GETFL, 0);  
  1160.     flags |= O_NONBLOCK;  
  1161. int ret = ::fcntl(sockfd, F_SETFL, flags);  
  1162.     flags = ::fcntl(sockfd, F_GETFD, 0);  
  1163.     flags |= FD_CLOEXEC;  
  1164.     ret = ::fcntl(sockfd, F_SETFD, flags);  
  1165. }  
  1166. int createNonblockingOrDie()  
  1167. {//socket()创建非阻塞的socket描述符
  1168.     #if VALGRIND
  1169. int sockfd = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  
  1170. if (sockfd < 0) {  
  1171.         printf("socket() error\n");  
  1172.     }  
  1173.     setNonBlockAndCloseOnExec(sockfd);  
  1174.     #else
  1175. int sockfd = ::socket(AF_INET,  
  1176.                         SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC,  
  1177.                         IPPROTO_TCP);  
  1178. if (sockfd < 0){  
  1179.         printf("socke() error\n");  
  1180.     }  
  1181.     #endif
  1182. return sockfd;  
  1183. }  
  1184. int connect(int sockfd,const struct sockaddr_in& addr){  
  1185. return ::connect(sockfd,sockaddr_cast(&addr),sizeof addr);  
  1186. }  
  1187. void bindOrDie(int sockfd, const struct sockaddr_in& addr)  
  1188. {//bind()
  1189. int ret = ::bind(sockfd, sockaddr_cast(&addr), sizeof addr);  
  1190. if (ret < 0) {  
  1191.          printf("bind() error\n");  
  1192.     }  
  1193. }  
  1194. void listenOrDie(int sockfd){//listen()
  1195. int ret = ::listen(sockfd, SOMAXCONN);  
  1196. if (ret < 0){  
  1197.           printf("listen() error\n");  
  1198.     }  
  1199. }  
  1200. int accept(int sockfd, struct sockaddr_in* addr)  
  1201. {//accept()
  1202.     socklen_t addrlen = sizeof *addr;  
  1203.     #if VALGRIND
  1204. int connfd = ::accept(sockfd, sockaddr_cast(addr), &addrlen);  
  1205.     setNonBlockAndCloseOnExec(connfd);  
  1206.     #else
  1207. int connfd = ::accept4(sockfd, sockaddr_cast(addr),  
  1208.                          &addrlen, SOCK_NONBLOCK | SOCK_CLOEXEC);  
  1209.     #endif
  1210. if (connfd < 0){  
  1211. int savedErrno = errno;  
  1212.         printf("accept error\n");  
  1213. switch (savedErrno)  
  1214.         {  
  1215. case EAGAIN:  
  1216. case ECONNABORTED:  
  1217. case EINTR:  
  1218. case EPROTO: // ???
  1219. case EPERM:  
  1220. case EMFILE: // per-process lmit of open file desctiptor ???
  1221.                 errno = savedErrno;  
  1222. break;  
  1223. case EBADF:  
  1224. case EFAULT:  
  1225. case EINVAL:  
  1226. case ENFILE:  
  1227. case ENOBUFS:  
  1228. case ENOMEM:  
  1229. case ENOTSOCK:  
  1230. case EOPNOTSUPP:  
  1231.                 printf("accept() fatal erro\n");  
  1232. break;  
  1233. default:  
  1234.                 printf("accpet() unknown error\n");  
  1235. break;  
  1236.         }  
  1237.     }  
  1238. return connfd;  
  1239. }  
  1240. void close(int sockfd){//close()
  1241. if (::close(sockfd) < 0){  
  1242.         printf("sockets::close\n");  
  1243.     }  
  1244. }  
  1245. void shutdownWrite(int sockfd){  
  1246. if(::shutdown(sockfd,SHUT_WR)<0)  
  1247.         printf("sockets::shutdownWrite() error\n");  
  1248. }  
  1249. void toHostPort(char* buf, size_t size,const struct sockaddr_in& addr)  
  1250. {//将IPv4地址转为IP和端口
  1251. char host[INET_ADDRSTRLEN] = "INVALID";  
  1252.     ::inet_ntop(AF_INET, &addr.sin_addr, host, sizeof host);  
  1253.     uint16_t port =networkToHost16(addr.sin_port);  
  1254.     snprintf(buf, size, "%s:%u", host, port);  
  1255. }  
  1256. void fromHostPort(const char* ip, uint16_t port,struct sockaddr_in* addr)  
  1257. {//将主机IP和端口转为IPv4地址
  1258.     addr->sin_family = AF_INET;  
  1259.     addr->sin_port = hostToNetwork16(port);  
  1260. if (::inet_pton(AF_INET, ip, &addr->sin_addr) <= 0)  
  1261.     {  
  1262.         printf("sockets::fromHostPort\n");  
  1263.     }  
  1264. }  
  1265. sockaddr_in getLocalAddr(int sockfd)  
  1266. {  
  1267. struct sockaddr_in localaddr;  
  1268.   bzero(&localaddr, sizeof localaddr);  
  1269.   socklen_t addrlen = sizeof(localaddr);  
  1270. if (::getsockname(sockfd, sockaddr_cast(&localaddr), &addrlen) < 0)  
  1271.   {  
  1272.       printf("getsockname() error\n");  
  1273.   }  
  1274. return localaddr;  
  1275. }  
  1276. struct sockaddr_in getPeerAddr(int sockfd){  
  1277. struct sockaddr_in peeraddr;  
  1278.     bzero(&peeraddr,sizeof peeraddr);  
  1279.     socklen_t addrlen=sizeof peeraddr;  
  1280. if(::getpeername(sockfd,sockaddr_cast(&peeraddr),&addrlen)<0)  
  1281.         printf("sockets::getPeerAddr() error\n");  
  1282. return peeraddr;  
  1283. }  
  1284. int getSocketError(int sockfd){  
  1285. int optval;  
  1286.     socklen_t optlen=sizeof optval;  
  1287. if(getsockopt(sockfd,SOL_SOCKET,SO_ERROR,&optval,&optlen)<0){  
  1288. return errno;  
  1289.     }  
  1290. else{  
  1291. return optval;  
  1292.     }  
  1293. }  
  1294. bool isSelfConnect(int sockfd){//自连接判断
  1295. struct sockaddr_in localaddr=getLocalAddr(sockfd);  
  1296. struct sockaddr_in peeraddr=getPeerAddr(sockfd);  
  1297. return localaddr.sin_port==peeraddr.sin_port&&  
  1298.         localaddr.sin_addr.s_addr==peeraddr.sin_addr.s_addr;  
  1299. }  
  1300. }//end-namespace
  1301. /*
  1302.  * Socket
  1303.  */
  1304. class InetAddress;  
  1305. class Socket:noncopyable{//创建一个socket描述符fd并绑定sockaddr,监听fd功能
  1306. public:  
  1307. explicit Socket(uint16_t sockfd):sockfd_(sockfd){}  
  1308.         ~Socket();  
  1309. int fd() const{return sockfd_;}  
  1310. void bindAddress(const InetAddress& addr);  
  1311. void listen();  
  1312. int accept(InetAddress* peeraddr);  
  1313. void setReuseAddr(bool on);  
  1314. void shutdownWrite(){  
  1315.             sockets::shutdownWrite(sockfd_);  
  1316.         }  
  1317. void setTcpNoDelay(bool on){  
  1318. int optval=on?1:0;  
  1319.             ::setsockopt(sockfd_,IPPROTO_TCP,TCP_NODELAY,&optval,sizeof optval);  
  1320.         }  
  1321. private:  
  1322. const int sockfd_;  
  1323. };  
  1324. /*
  1325.  * sockaddr_in
  1326.  */
  1327. class InetAddress{//sockaddr地址的封装
  1328. public:  
  1329. explicit InetAddress(uint16_t port);  
  1330.         InetAddress(const string& ip,uint16_t port);  
  1331.         InetAddress(const struct sockaddr_in& addr):addr_(addr){}  
  1332.         string toHostPort() const;  
  1333. const struct sockaddr_in& getSockAddrInet() const{return addr_;}  
  1334. void setSockAddrInet(const struct sockaddr_in& addr){addr_=addr;}  
  1335. private:  
  1336. struct sockaddr_in addr_;  
  1337. };  
  1338. BOOST_STATIC_ASSERT(sizeof(InetAddress)==sizeof(struct sockaddr_in));//编译时断言
  1339. class Acceptor:noncopyable{//接受TCP连接并执行相应的回调
  1340. public://Acceptor对应的是一个服务端的监听socket描述符listenfd
  1341. typedef function<void(int sockfd,const InetAddress&)> NewConnectionCallback;  
  1342.         Acceptor(EventLoop* loop,const InetAddress& listenAddr);  
  1343. void setNewConnectionCallback(const NewConnectionCallback& cb)  
  1344.         { newConnectionCallback_=cb;}  
  1345. bool listening() const{return listening_;}  
  1346. void listen();  
  1347. private:  
  1348. void handleRead();  
  1349.         EventLoop* loop_;  
  1350.         Socket acceptSocket_;//服务端listenfd对应RAII封装的socket描述符
  1351.         Channel acceptChannel_;//采用Channel管理服务端监听端口listenfd,可以理解为Channel管理accpetSocket_里的fd
  1352.         NewConnectionCallback newConnectionCallback_;  
  1353. bool listening_;  
  1354. };  
  1355. /*
  1356.  *Socket实现
  1357.  */
  1358. Socket::~Socket()  
  1359. {  
  1360.     sockets::close(sockfd_);  
  1361. }  
  1362. void Socket::bindAddress(const InetAddress& addr)  
  1363. {  
  1364.     sockets::bindOrDie(sockfd_, addr.getSockAddrInet());  
  1365. }  
  1366. void Socket::listen()  
  1367. {  
  1368.     sockets::listenOrDie(sockfd_);  
  1369. }  
  1370. int Socket::accept(InetAddress* peeraddr)  
  1371. {  
  1372. struct sockaddr_in addr;  
  1373.     bzero(&addr, sizeof addr);  
  1374. int connfd = sockets::accept(sockfd_, &addr);  
  1375. if (connfd >= 0)  
  1376.     {  
  1377.         peeraddr->setSockAddrInet(addr);  
  1378.     }  
  1379. return connfd;  
  1380. }  
  1381. void Socket::setReuseAddr(bool on)  
  1382. {  
  1383. int optval = on ? 1 : 0;  
  1384.     ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR,  
  1385.                &optval, sizeof optval);  
  1386. }  
  1387. /*
  1388.  *InetAddress实现
  1389.  */
  1390. static const in_addr_t kInaddrAny=INADDR_ANY;//任意的网络字节序IP地址为0
  1391. InetAddress::InetAddress(uint16_t port)  
  1392. {  
  1393.     bzero(&addr_, sizeof addr_);  
  1394.     addr_.sin_family = AF_INET;  
  1395.     addr_.sin_addr.s_addr = sockets::hostToNetwork32(kInaddrAny);  
  1396.     addr_.sin_port = sockets::hostToNetwork16(port);  
  1397. }  
  1398. InetAddress::InetAddress(const std::string& ip, uint16_t port)  
  1399. {  
  1400.     bzero(&addr_, sizeof addr_);  
  1401.     sockets::fromHostPort(ip.c_str(), port, &addr_);  
  1402. }  
  1403. string InetAddress::toHostPort() const
  1404. {  
  1405. char buf[32];  
  1406.     sockets::toHostPort(buf, sizeof buf, addr_);  
  1407. return buf;  
  1408. }  
  1409. /*
  1410.  *Acceptor实现
  1411.  */
  1412. Acceptor::Acceptor(EventLoop* loop, const InetAddress& listenAddr)  
  1413.   : loop_(loop),  
  1414.     acceptSocket_(sockets::createNonblockingOrDie()),  
  1415.     acceptChannel_(loop, acceptSocket_.fd()),  
  1416.     listening_(false)  
  1417. {  
  1418.     acceptSocket_.setReuseAddr(true);  
  1419.     acceptSocket_.bindAddress(listenAddr);  
  1420.     acceptChannel_.setReadCallback(  
  1421.       boost::bind(&Acceptor::handleRead, this));  
  1422. }  
  1423. void Acceptor::listen()  
  1424. {  
  1425.     loop_->assertInLoopThread();  
  1426.     listening_ = true;  
  1427.     acceptSocket_.listen();  
  1428.     acceptChannel_.enableReading();  
  1429. }  
  1430. void Acceptor::handleRead()  
  1431. {  
  1432.     loop_->assertInLoopThread();  
  1433.     InetAddress peerAddr(0);  
  1434. int connfd = acceptSocket_.accept(&peerAddr);  
  1435. if (connfd >= 0) {  
  1436. if (newConnectionCallback_) {  
  1437.             newConnectionCallback_(connfd, peerAddr);  
  1438.         } else {  
  1439.             sockets::close(connfd);  
  1440.         }  
  1441.     }  
  1442. }  
  1443. /*
  1444.  *Buffer管理数据接收与发送
  1445.  */
  1446. class Buffer{//copyable
  1447. public:  
  1448. static const size_t kCheapPrepend=8;  
  1449. static const size_t kInitialSize=1024;  
  1450.         Buffer():buffer_(kCheapPrepend+kInitialSize),  
  1451.             readerIndex_(kCheapPrepend),writerInex_(kCheapPrepend)  
  1452.         {  
  1453.             assert(readableBytes()==0);  
  1454.             assert(writeableBytes()==kInitialSize);  
  1455.             assert(prependableBytes()==kCheapPrepend);  
  1456.         }  
  1457. void swap(Buffer& rhs){  
  1458.             buffer_.swap(rhs.buffer_);  
  1459.             std::swap(readerIndex_,rhs.readerIndex_);  
  1460.             std::swap(writerInex_,rhs.writerInex_);  
  1461.         }  
  1462. size_t readableBytes() const{  
  1463. return writerInex_-readerIndex_;  
  1464.         }//返回Buffer中多少数据
  1465. size_t writeableBytes() const{  
  1466. return buffer_.size()-writerInex_;  
  1467.         }//返回还有多少剩余空间
  1468. size_t prependableBytes() const{  
  1469. return readerIndex_;  
  1470.         }//返回可读位置
  1471. const char* peek() const{  
  1472. return begin()+readerIndex_;  
  1473.         }//第一个可读的字节处
  1474. void retrieve(size_t len){  
  1475.             assert(len<=readableBytes());  
  1476.             readerIndex_+=len;  
  1477.         }//一次性没有读完,readerindex_移动
  1478. void retrieveUntil(const char* end){  
  1479.             assert(peek()<=end);  
  1480.             assert(end<=beginWrite());//beginwrite()返回第一个可写的位置
  1481.             retrieve(end-peek());  
  1482.         }//返回有多少Buffer中可读字节
  1483. void retrieveAll(){  
  1484.             readerIndex_=kCheapPrepend;  
  1485.             writerInex_=kCheapPrepend;  
  1486.         }//重置Buffer
  1487.         std::string retrieveAsString(){  
  1488.             string str(peek(),readableBytes());  
  1489.             retrieveAll();  
  1490. return str;  
  1491.         }//以string返回Buffer中数据,并重置Buffer
  1492. void append(const string& str){  
  1493.             append(str.data(),str.length());  
  1494.         }  
  1495. void append(const char* data,size_t len){  
  1496.             ensureWriteableBytes(len);//空间不足会调用makespace扩容或者内部腾挪
  1497.             std::copy(data,data+len,beginWrite());//copy(Input first,Input last,Output)
  1498.             hasWritten(len);//更新writerinex_
  1499.         }  
  1500. void append(const void* data,size_t len){  
  1501.             append(static_cast<const char*>(data),len);  
  1502.         }  
  1503. void ensureWriteableBytes(size_t len){  
  1504. if(writeableBytes()<len){  
  1505.                 makeSpace(len);  
  1506.             }//若剩余空间不够,则重新分配空间
  1507.             assert(writeableBytes()>=len);  
  1508.         }  
  1509. char* beginWrite(){  
  1510. return begin()+writerInex_;  
  1511.         }//可以写的位置
  1512. const char* beginWrite() const{  
  1513. return begin()+writerInex_;  
  1514.         }  
  1515. void hasWritten(size_t len){  
  1516.             writerInex_+=len;  
  1517.         }//更新writerinex_
  1518. void prepend(const void* data,size_t len){  
  1519.             assert(len<=prependableBytes());  
  1520.             readerIndex_-=len;  
  1521. const char* d=static_cast<const char*>(data);  
  1522.             std::copy(d,d+len,begin()+readerIndex_);  
  1523.         }//前向添加数据
  1524. void shrink(size_t reserve){  
  1525.             vector<char> buf(kCheapPrepend+readableBytes()+reserve);  
  1526.             std::copy(peek(),peek()+readableBytes(),buf.begin()+kCheapPrepend);  
  1527.             buf.swap(buffer_);  
  1528.         }//重置Buffer大小
  1529.         ssize_t readFd(int fd,int* savedErrno){  
  1530. char extrabuf[65536];//栈空间,vector在堆空间
  1531. struct iovec vec[2];  
  1532. const size_t writeable=writeableBytes();  
  1533.             vec[0].iov_base=begin()+writerInex_;  
  1534.             vec[0].iov_len=writeable;  
  1535.             vec[1].iov_base=extrabuf;  
  1536.             vec[1].iov_len=sizeof extrabuf;  
  1537. const ssize_t n=readv(fd,vec,2);//readv集中读
  1538. if(n<0){  
  1539.                 *savedErrno=errno;  
  1540.             }  
  1541. else if(implicit_cast<size_t>(n)<=writeable){  
  1542.                 writerInex_+=n;  
  1543.             }//Buffer还有剩余
  1544. else{  
  1545.                 writerInex_=buffer_.size();  
  1546.                 append(extrabuf,n-writeable);  
  1547.             }//Buffer不够,栈空间数据append到Buffer使Buffer慢慢变大
  1548. return n;  
  1549.         }  
  1550. private:  
  1551. char* begin(){//.>*>&首字符
  1552. return &*buffer_.begin();  
  1553.         }  
  1554. const char* begin() const{  
  1555. return &*buffer_.begin();  
  1556.         }  
  1557. void makeSpace(size_t len){//ensurewriteablebytes()->makespace()
  1558. //当剩余空间writeable()<len时被调用
  1559. if(writeableBytes()+prependableBytes()<len+kCheapPrepend){  
  1560.                 buffer_.resize(writerInex_+len);  
  1561.             }//(Buffer.size()-writerinex_剩余空间)+(readerindex_第一个可读位置)<
  1562. //len+前向大小,这时无论怎样腾挪都不够写了,需要追加Buffer的大小
  1563. else{//可以通过腾挪满足len大小的写入
  1564.                 assert(kCheapPrepend<readerIndex_);  
  1565. size_t readable=readableBytes();  
  1566.                 std::copy(begin()+readerIndex_,begin()+writerInex_,begin()+kCheapPrepend);//Buffer的已有数据向前腾挪
  1567.                 readerIndex_=kCheapPrepend;//readerindex_回到初始位置
  1568.                 writerInex_=readerIndex_+readable;  
  1569.                 assert(readable==readableBytes());  
  1570.             }  
  1571.         }  
  1572. private:  
  1573.         vector<char> buffer_;  
  1574. size_t readerIndex_;  
  1575. size_t writerInex_;  
  1576. };  
  1577. class TcpConnection;//表示一个TCP连接
  1578. typedef shared_ptr<TcpConnection> TcpConnectionPtr;//
  1579. /*
  1580.  *TcpConnection
  1581.  */
  1582. class TcpConnection:noncopyable,public enable_shared_from_this<TcpConnection>{  
  1583. public:  
  1584.         TcpConnection(EventLoop* loop,const string& name,int sockfd,  
  1585. const InetAddress& localAddr,const InetAddress& peerAddr);  
  1586.         ~TcpConnection();  
  1587.         EventLoop* getLoop() const{return loop_;}  
  1588. const string& name() const{return name_;}  
  1589. const InetAddress& localAddr(){return localAddr_;}  
  1590. const InetAddress& peerAddress(){return peerAddr_;}  
  1591. bool connected() const{return state_==kConnected;}  
  1592. void send(const string& message);//发送消息,为了线程安全其会调用Tcpconnection::sendInLoop()
  1593. void shutdown();//关闭TCP连接,为了保证线程安全其会调用Tcpconnection:shutdownInloop()
  1594. void setTcpNoDelay(bool on);//关闭Nagle算法
  1595. void setConnectionCallback(const ConnectionCallback& cb){  
  1596.             connectionCallback_=cb;  
  1597.         }//set*Callback系列函数是由用户通过Tcpserver::set*Callback指定并由TcpServer::newConnection()创建Tcpconnection对象时传递给Tcpconnection::set*Callback函数
  1598. void setMessageCallback(const MessageCallback& cb){  
  1599.             messageCallback_=cb;  
  1600.         }  
  1601. void setWriteCompleteCallback(const WriteCompleteCallback& cb){  
  1602.             writeCompleteCallback_=cb;  
  1603.         }  
  1604. void setCloseCallback(const CloseCallback& cb){  
  1605. //由TcpServer和TcpClient调用,解除它们中的TcpConnectionPtr
  1606.             closeCallback_=cb;  
  1607.         }  
  1608. void connectEstablished();//调用Channel::enableReading()向Poller事件表注册事件,并调用TcpConnection::connectionCallback_()完成用户指定的连接回调
  1609. //Acceptor::handleRead()->TcpServer::newConnection()->TcpConnection::connectEstablished()
  1610. void connectDestroyed();//连接销毁函数,调用Channel::diableAll()使Poller对sockfd_忽略,并调用Eventloop::removeChannel()移除sockfd_对应的Channel
  1611. //TcpServer::removeConnection()->EventLoop::runInLoop()->TcpServer::removeConnectionInLoop()->EventLoop::queueInLoop()->TcpConnection::connectDestroyed()
  1612. //这是TcpConenction析构前调用的最后一个函数,用于告诉用户连接已断开
  1613. //将TcpConenction状态置为kDisconnected,Channel::diableAll(),connectioncallback_(),EventLoop::removeChannel()
  1614. private:  
  1615. enum StateE{kConnecting,kConnected,kDisconnecting,kDisconnected,};  
  1616. //Tcpconnection有四个状态:正在连接,已连接,正在断开,已断开
  1617. void setState(StateE s){state_=s;}  
  1618. void handleRead();  
  1619. //Tcpconnection::handle*系列函数是由Poller返回sockfd_上就绪事件后由Channel::handelEvent()调用的就绪事件回调函数
  1620. void handleWrite();  
  1621. void handleClose();  
  1622. void handleError();  
  1623. void sendInLoop(const string& message);  
  1624. void shutdownInLoop();  
  1625.         EventLoop* loop_;  
  1626.         string name_;  
  1627.         StateE state_;  
  1628.         scoped_ptr<Socket> socket_;//TcpConnection对应的那个TCP客户连接封装为socket_
  1629.         scoped_ptr<Channel> channel_;//TcpConnection对应的TCP客户连接connfd采用Channel管理
  1630.         InetAddress localAddr_;//TCP连接对应的服务端地址
  1631.         InetAddress peerAddr_;//TCP连接的客户端地址
  1632.         ConnectionCallback connectionCallback_;  
  1633. //用户指定的连接回调函数,TcpServer::setConenctionCallback()->Acceptor::handleRead()->Tcpserver::newConnection()->TcpConnection::setConnectionCallback()
  1634. //即TcpServer::setConenctionCallback()接收用户注册的连接回调,并通过Acceptor::handleRead()->Tcpserver::newConnection()将此用户连接回调函数传给Tcpconnection
  1635.         MessageCallback messageCallback_;//用户指定的消息处理函数,也是经由Tcpserver传给Tcpconnection
  1636.         WriteCompleteCallback writeCompleteCallback_;  
  1637.         CloseCallback closeCallback_;  
  1638.         Buffer inputBuffer_;  
  1639.         Buffer outputBuffer_;  
  1640. };  
  1641. /*
  1642.  *Tcpserver
  1643.  */
  1644. class TcpServer:noncopyable{//管理所有的TCP连接
  1645. public:  
  1646.         TcpServer(EventLoop* loop,const InetAddress& listenAddr);//构造时就有个监听端口的地址
  1647.         ~TcpServer();  
  1648. void setThreadNum(int numThreads);  
  1649. void start();  
  1650. void setConnectionCallback(const ConnectionCallback& cb){  
  1651.             connectionCallback_=cb;  
  1652.         }//TCP客户连接回调在TcpConnection里,TcpConnection::connectEstablished()->TcpConnection::connectionCallback_()
  1653. void setMessageCallback(const MessageCallback& cb){  
  1654.             messageCallback_=cb;  
  1655.         }//此回调将传给TcpConnection::setMessageCallback()作为TcpConenction的消息回调
  1656. void setWriteCompleteCallback(const WriteCompleteCallback& cb){  
  1657.             writeCompleteCallback_=cb;  
  1658.         }  
  1659. private:  
  1660. void newConnection(int sockfd,const InetAddress& peerAddr);  
  1661. void removeConnection(const TcpConnectionPtr& conn);  
  1662. void removeConnectionInLoop(const TcpConnectionPtr& conn);  
  1663. typedef map<string,TcpConnectionPtr> ConnectionMap;  
  1664.         EventLoop* loop_;  
  1665. const string name_;  
  1666.         scoped_ptr<Acceptor> acceptor_;//监听端口接受连接
  1667.         scoped_ptr<EventLoopThreadPool> threadPool_;//开启EventLoopThreadPool管理TCP连接
  1668.         ConnectionCallback connectionCallback_;//传给TcpConnection::setConnectionCallback(connectioncallback_)
  1669.         MessageCallback messageCallback_;//传给TcpConnection::setMessageCallback(messagecallback_)
  1670.         WriteCompleteCallback writeCompleteCallback_;  
  1671. bool started_;  
  1672. int nextConnId_;//用于标识TcpConnection,name_+nextConnId_就构成了一个TcpConnection的名字
  1673.         ConnectionMap connections_;//该TcpServer管理的所有TCP客户连接存放的容器
  1674. };  
  1675. /*
  1676.  *TcpConnection实现
  1677.  */
  1678. TcpConnection::TcpConnection(EventLoop* loop,  
  1679. const std::string& nameArg,  
  1680. int sockfd,  
  1681. const InetAddress& localAddr,  
  1682. const InetAddress& peerAddr)  
  1683.     : loop_(loop),  
  1684.     name_(nameArg),  
  1685.     state_(kConnecting),  
  1686.     socket_(new Socket(sockfd)),  
  1687.     channel_(new Channel(loop, sockfd)),  
  1688.     localAddr_(localAddr),  
  1689.     peerAddr_(peerAddr)  
  1690. {  
  1691.     channel_->setReadCallback(bind(&TcpConnection::handleRead, this));  
  1692.     channel_->setWriteCallback(bind(&TcpConnection::handleWrite,this));  
  1693.     channel_->setCloseCallback(bind(&TcpConnection::handleClose,this));  
  1694.     channel_->setErrorCallback(bind(&TcpConnection::handleError,this));  
  1695. }  
  1696. TcpConnection::~TcpConnection()  
  1697. {  
  1698.     printf("TcpConnection::%s,fd=%d\n",name_.c_str(),channel_->fd());  
  1699. }  
  1700. void TcpConnection::send(const string& message){  
  1701.     cout<<"TcpConnection::send() ##"<<message<<endl;  
  1702. if(state_==kConnected){  
  1703. if(loop_->isInLoopThread()){  
  1704.             sendInLoop(message);  
  1705.         }  
  1706. else{  
  1707.             loop_->runInLoop(bind(&TcpConnection::sendInLoop,this,message));  
  1708.         }  
  1709.     }  
  1710. }  
  1711. void TcpConnection::sendInLoop(const string& message){  
  1712. //若TcpConnection的socket已经注册了可写事件即outputBuffer_已经有数据了则直接调用Buffer::append
  1713. //若socket的Channel没有注册可读则表明outputbuffer_没有数据存留,则可以直接先write发送
  1714. //若write一次性没有发送完,则剩下数据需要append到outputbuffer_
  1715. //若write一次性发送完毕则需要执行writecompletecallback_
  1716.     loop_->assertInLoopThread();  
  1717.     ssize_t nwrote=0;  
  1718.     cout<<message<<endl;  
  1719. if(!channel_->isWriting()&&outputBuffer_.readableBytes()==0){  
  1720.         nwrote=write(channel_->fd(),message.data(),message.size());  
  1721. if(nwrote>=0){  
  1722. if(implicit_cast<size_t>(nwrote)<message.size()){  
  1723.                 printf("I am going to write more data\n");  
  1724.             }  
  1725. else if(writeCompleteCallback_){  
  1726.                 loop_->queueInLoop(bind(writeCompleteCallback_,shared_from_this()));  
  1727.             }  
  1728.         }  
  1729. else{  
  1730.             nwrote=0;  
  1731. if(errno!=EWOULDBLOCK){  
  1732.                 printf("TcpConnection::sendInLoop() error\n");  
  1733.             }  
  1734.         }  
  1735.     }  
  1736.     assert(nwrote>=0);  
  1737. if(implicit_cast<size_t>(nwrote)<message.size()){  
  1738.         outputBuffer_.append(message.data()+nwrote,message.size()-nwrote);  
  1739. if(!channel_->isWriting()){  
  1740.            channel_->enableWriting();  
  1741.         }  
  1742.     }  
  1743. }  
  1744. void TcpConnection::shutdown(){  
  1745. if(state_==kConnected){  
  1746.         setState(kDisconnecting);  
  1747.         loop_->runInLoop(bind(&TcpConnection::shutdownInLoop,this));  
  1748.     }  
  1749. }  
  1750. void TcpConnection::shutdownInLoop(){  
  1751.     loop_->assertInLoopThread();  
  1752. if(!channel_->isWriting()){  
  1753.         socket_->shutdownWrite();  
  1754.     }  
  1755. }  
  1756. void TcpConnection::setTcpNoDelay(bool on){  
  1757.     socket_->setTcpNoDelay(on);  
  1758. }  
  1759. void TcpConnection::connectEstablished()  
  1760. {  
  1761.     loop_->assertInLoopThread();  
  1762.     assert(state_ == kConnecting);  
  1763.     setState(kConnected);  
  1764.     channel_->enableReading();  
  1765.     connectionCallback_(shared_from_this());//连接建立回调函数
  1766. }  
  1767. void TcpConnection::handleRead()  
  1768. {  
  1769. int savedErrno=0;  
  1770.     ssize_t n =inputBuffer_.readFd(channel_->fd(),&savedErrno);//readv()
  1771. if(n>0)  
  1772.         messageCallback_(shared_from_this(),&inputBuffer_);  
  1773. else if(n==0)  
  1774.         handleClose();  
  1775. else{  
  1776.         errno=savedErrno;  
  1777.         printf("TcpConnection::hanleRead() error\n");  
  1778.         handleError();  
  1779.     }  
  1780. }  
  1781. void TcpConnection::handleWrite(){  
  1782.     loop_->assertInLoopThread();  
  1783. if(channel_->isWriting()){  
  1784.         ssize_t n=write(channel_->fd(),outputBuffer_.peek(),outputBuffer_.readableBytes());  
  1785. if(n>0){//peek()返回第一个可读的字节,readablebytes()返回Buffer中数据的大小
  1786.             outputBuffer_.retrieve(n);//readerindex_+=n更新Buffer的读位置
  1787. if(outputBuffer_.readableBytes()==0){//如果Buffer里还有数据未发送的话不会立即调用shutdownwrite而是等待数据发送完毕再shutdown
  1788.                 channel_->disableWriting();//防止busy loop
  1789. if(writeCompleteCallback_){  
  1790.                     loop_->queueInLoop(bind(writeCompleteCallback_,shared_from_this()));  
  1791.                 }  
  1792. if(state_==kDisconnecting)  
  1793.                     shutdownInLoop();  
  1794.             }  
  1795. else
  1796.                 printf("I am going to write more data\n");  
  1797.         }  
  1798. else
  1799.             printf("TcpConnection::handleWrite()\n");  
  1800.     }  
  1801. else
  1802.         printf("Connection is down,no more writing\n");  
  1803. }  
  1804. void TcpConnection::handleClose(){  
  1805.     loop_->assertInLoopThread();  
  1806.     assert(state_==kConnected||state_==kDisconnecting);  
  1807.     channel_->disableAll();  
  1808.     closeCallback_(shared_from_this());  
  1809. }  
  1810. void TcpConnection::handleError(){  
  1811. int err=sockets::getSocketError(channel_->fd());  
  1812.     printf("TcpConnection::handleError() %d %s\n",err,strerror(err));  
  1813. }  
  1814. void TcpConnection::connectDestroyed(){  
  1815.     loop_->assertInLoopThread();  
  1816.     printf("TcpConnection::handleClose() state=%s\n",state_);  
  1817.     assert(state_==kConnected||state_==kDisconnected);  
  1818.     setState(kDisconnected);  
  1819.     channel_->disableAll();  
  1820.     connectionCallback_(shared_from_this());  
  1821.     loop_->removeChannel(get_pointer(channel_));  
  1822. }  
  1823. /*
  1824.  *TcpServer实现
  1825.  */
  1826. TcpServer::TcpServer(EventLoop* loop, const InetAddressEventLoop::removeChannel()  
  1827.     name_(listenAddr.toHostPort()),  
  1828.     acceptor_(new Acceptor(loop, listenAddr)),  
  1829.     threadPool_(new EventLoopThreadPool(loop)),  
  1830.     started_(false),  
  1831.     nextConnId_(1))  
  1832. {  
  1833.     acceptor_->setNewConnectionCallback(bind(&TcpServer::newConnection, this, _1, _2));  
  1834. }  
  1835. TcpServer::~TcpServer()  
  1836. {  
  1837. }  
  1838. void TcpServer::setThreadNum(int numThreads){  
  1839.     assert(numThreads>=0);  
  1840.     threadPool_->setThreadNum(numThreads);  
  1841. }  
  1842. void TcpServer::start()  
  1843. {  
  1844. if (!started_)  
  1845.     {  
  1846.         started_ = true;  
  1847.     }  
  1848. if (!acceptor_->listening())  
  1849.     {  
  1850.         loop_->runInLoop(bind(&Acceptor::listen, get_pointer(acceptor_)));  
  1851.     }//通过EventLoop监听服务端的listenfd,shared_ptr.hpp中的get_pointer用于返回shared_ptr所管理对象的裸指针
  1852. }  
  1853. void TcpServer::newConnection(int sockfd, const InetAddress& peerAddr)  
  1854. {//用于Acceptor接受一个连接后通过此回调通知使用者
  1855.     loop_->assertInLoopThread();  
  1856. char buf[32];  
  1857.     snprintf(buf, sizeof buf, "#%d", nextConnId_);  
  1858.     ++nextConnId_;  
  1859.     string connName = name_ + buf;  
  1860.     InetAddress localAddr(sockets::getLocalAddr(sockfd));  
  1861.     EventLoop* ioLoop=threadPool_->getNextLoop();//选一个EventLoop给TcpConnection
  1862.     TcpConnectionPtr conn(  
  1863. new TcpConnection(ioLoop, connName, sockfd, localAddr, peerAddr));  
  1864.     connections_[connName]=conn;  
  1865.     conn->setConnectionCallback(connectionCallback_);//传递给TcpConnection
  1866.     conn->setMessageCallback(messageCallback_);  
  1867.     conn->setWriteCompleteCallback(writeCompleteCallback_);  
  1868.     conn->setCloseCallback(bind(&TcpServer::removeConnection,this,_1));//将移除TcpConnectionPtr的操作注册到TcpConnection::setCloseCallback
  1869.     ioLoop->runInLoop(bind(&TcpConnection::connectEstablished,conn));  
  1870. //通过EventLoop::runInLoop()->EventLoop::queueInLoop()->TcpConnection::connectEstablished()
  1871. }  
  1872. void TcpServer::removeConnection(const TcpConnectionPtr& conn){  
  1873.     loop_->runInLoop(bind(&TcpServer::removeConnectionInLoop,this,conn));  
  1874. //TcpServer::removeConnection()->EventLoop::runInLoop()->EventLoop::queueInLoop()->TcpServer::removeConnectionInLoop()
  1875. }  
  1876. void TcpServer::removeConnectionInLoop(const TcpConnectionPtr& conn){  
  1877.     loop_->assertInLoopThread();  
  1878. size_t n=connections_.erase(conn->name());  
  1879.     assert(n==1);  
  1880.     (void)n;  
  1881.     EventLoop* ioLoop=conn->getLoop();  
  1882.     ioLoop->queueInLoop(bind(&TcpConnection::connectDestroyed,conn));//在IO线程内完成直接EventLoop::queueInLoop()
  1883. }  
  1884. /*
  1885.  * 发起连接
  1886.  */
  1887. class Connector : boost::noncopyable  
  1888. {  
  1889. public:  
  1890. typedef function<void (int sockfd)> NewConnectionCallback;  
  1891.         Connector(EventLoop* loop, const InetAddress& serverAddr);  
  1892.         ~Connector();  
  1893. void setNewConnectionCallback(const NewConnectionCallback& cb)  
  1894.         { newConnectionCallback_ = cb; }  
  1895. void start();  // can be called in any thread
  1896. void restart();  // must be called in loop thread
  1897. void stop();  // can be called in any thread
  1898. const InetAddress& serverAddress() const { return serverAddr_; }  
  1899. private:  
  1900. enum States { kDisconnected, kConnecting, kConnected };  
  1901. //未连接,正在连接,已连接
  1902. static const int kMaxRetryDelayMs = 30*1000;  
  1903. static const int kInitRetryDelayMs = 500;  
  1904. void setState(States s) { state_ = s; }  
  1905. void startInLoop();  
  1906. void connect();  
  1907. void connecting(int sockfd);  
  1908. void handleWrite();  
  1909. void handleError();  
  1910. void retry(int sockfd);  
  1911. int removeAndResetChannel();  
  1912. void resetChannel();  
  1913.         EventLoop* loop_;  
  1914.         InetAddress serverAddr_;  
  1915. bool connect_; // atomic
  1916.         States state_;  // FIXME: use atomic variable
  1917.         boost::scoped_ptr<Channel> channel_;  
  1918.         NewConnectionCallback newConnectionCallback_;  
  1919. int retryDelayMs_;  
  1920.         TimerId timerId_;  
  1921. };  
  1922. /*
  1923.  * Connector实现
  1924.  */
  1925. typedef boost::shared_ptr<Connector> ConnectorPtr;  
  1926. const int Connector::kMaxRetryDelayMs;  
  1927. Connector::Connector(EventLoop* loop, const InetAddress& serverAddr)  
  1928.     :loop_(loop),  
  1929.     serverAddr_(serverAddr),  
  1930.     connect_(false),  
  1931.     state_(kDisconnected),  
  1932.     retryDelayMs_(kInitRetryDelayMs)  
  1933. {  
  1934. }  
  1935. Connector::~Connector()  
  1936. {  
  1937.     loop_->cancel(timerId_);  
  1938.     assert(!channel_);  
  1939. }  
  1940. void Connector::start()  
  1941. {//可以由其它线程调用
  1942.     connect_ = true;  
  1943.     loop_->runInLoop(boost::bind(&Connector::startInLoop, this)); // FIXME: unsafe
  1944. }  
  1945. void Connector::startInLoop()  
  1946. {  
  1947.     loop_->assertInLoopThread();  
  1948.     assert(state_ == kDisconnected);  
  1949. if (connect_)  
  1950.     {  
  1951.         connect();//
  1952.     }  
  1953. else
  1954.     {}  
  1955. }  
  1956. void Connector::connect()  
  1957. {  
  1958. int sockfd = sockets::createNonblockingOrDie();  
  1959. int ret = sockets::connect(sockfd, serverAddr_.getSockAddrInet());  
  1960. int savedErrno = (ret == 0) ? 0 : errno;  
  1961. switch (savedErrno)  
  1962.     {  
  1963. case 0:  
  1964. case EINPROGRESS:  
  1965. case EINTR:  
  1966. case EISCONN:  
  1967.             connecting(sockfd);  
  1968. break;  
  1969. case EAGAIN:  
  1970. case EADDRINUSE:  
  1971. case EADDRNOTAVAIL:  
  1972. case ECONNREFUSED:  
  1973. case ENETUNREACH:  
  1974.             retry(sockfd);  
  1975. break;  
  1976. case EACCES:  
  1977. case EPERM:  
  1978. case EAFNOSUPPORT:  
  1979. case EALREADY:  
  1980. case EBADF:  
  1981. case EFAULT:  
  1982. case ENOTSOCK:  
  1983.             sockets::close(sockfd);  
  1984. break;  
  1985. default:  
  1986.             sockets::close(sockfd);  
  1987. // connectErrorCallback_();
  1988. break;  
  1989.   }  
  1990. }  
  1991. void Connector::restart()  
  1992. {  
  1993.     loop_->assertInLoopThread();  
  1994.     setState(kDisconnected);  
  1995.     retryDelayMs_ = kInitRetryDelayMs;  
  1996.     connect_ = true;  
  1997.     startInLoop();  
  1998. }  
  1999. void Connector::stop()  
  2000. {  
  2001.     connect_ = false;  
  2002.     loop_->cancel(timerId_);  
  2003. }  
  2004. void Connector::connecting(int sockfd)  
  2005. {//EINPROGRESS
  2006.     setState(kConnecting);  
  2007.     assert(!channel_);  
  2008.     channel_.reset(new Channel(loop_, sockfd));  
  2009.     channel_->setWriteCallback(bind(&Connector::handleWrite, this)); // FIXME: unsafe
  2010.     channel_->setErrorCallback(bind(&Connector::handleError, this)); // FIXME: unsafe
  2011.     channel_->enableWriting();  
  2012. }  
  2013. int Connector::removeAndResetChannel()  
  2014. {  
  2015.     channel_->disableAll();  
  2016.     loop_->removeChannel(get_pointer(channel_));  
  2017. int sockfd = channel_->fd();  
  2018.     loop_->queueInLoop(bind(&Connector::resetChannel, this)); // FIXME: unsafe
  2019. return sockfd;  
  2020. }  
  2021. void Connector::resetChannel()  
  2022. {  
  2023.     channel_.reset();  
  2024. }  
  2025. void Connector::handleWrite()  
  2026. {  
  2027. if (state_ == kConnecting)  
  2028.     {  
  2029. int sockfd = removeAndResetChannel();  
  2030. int err = sockets::getSocketError(sockfd);  
  2031. if (err)  
  2032.             retry(sockfd);  
  2033. else if (sockets::isSelfConnect(sockfd))  
  2034.             retry(sockfd);  
  2035. else
  2036.         {  
  2037.             setState(kConnected);  
  2038. if (connect_)  
  2039.                 newConnectionCallback_(sockfd);  
  2040. else
  2041.                 sockets::close(sockfd);  
  2042.         }  
  2043.     }  
  2044. else
  2045.     {  
  2046.         assert(state_ == kDisconnected);  
  2047.     }  
  2048. }  
  2049. void Connector::handleError()  
  2050. {  
  2051.     assert(state_ == kConnecting);  
  2052. int sockfd = removeAndResetChannel();  
  2053. int err = sockets::getSocketError(sockfd);  
  2054.     retry(sockfd);  
  2055. }  
  2056. void Connector::retry(int sockfd)  
  2057. {//EAGAIN
  2058.     sockets::close(sockfd);  
  2059.     setState(kDisconnected);  
  2060. if (connect_){  
  2061.         timerId_ = loop_->runAfter(retryDelayMs_/1000.0,  // FIXME: unsafe
  2062.                                boost::bind(&Connector::startInLoop, this));  
  2063.         retryDelayMs_ = std::min(retryDelayMs_ * 2, kMaxRetryDelayMs);  
  2064.     }  
  2065. else
  2066.     {}  
  2067. }  
  2068. /*
  2069.  * TcpClient
  2070.  */
  2071. typedef boost::shared_ptr<Connector> ConnectorPtr;  
  2072. class TcpClient : boost::noncopyable  
  2073. {  
  2074. public:  
  2075.         TcpClient(EventLoop* loop,  
  2076. const InetAddress& serverAddr,  
  2077. const string& name);  
  2078.      ~TcpClient();  // force out-line dtor, for scoped_ptr members.
  2079. void connect();  
  2080. void disconnect();  
  2081. void stop();  
  2082.         TcpConnectionPtr connection() const
  2083.         {  
  2084.             MutexLockGuard lock(mutex_);  
  2085. return connection_;  
  2086.         }  
  2087.         EventLoop* getLoop() const { return loop_; }  
  2088. bool retry() const;  
  2089. void enableRetry() { retry_ = true; }  
  2090. void setConnectionCallback(const ConnectionCallback& cb)  
  2091.         { connectionCallback_ = cb; }  
  2092. void setMessageCallback(const MessageCallback& cb)  
  2093.         { messageCallback_ = cb; }  
  2094. void setWriteCompleteCallback(const WriteCompleteCallback& cb)  
  2095.         { writeCompleteCallback_ = cb; }  
  2096.         #ifdef __GXX_EXPERIMENTAL_CXX0X__
  2097. void setConnectionCallback(ConnectionCallback&& cb)  
  2098.         { connectionCallback_ = cb; }  
  2099. void setMessageCallback(MessageCallback&& cb)  
  2100.         { messageCallback_ = cb; }  
  2101. void setWriteCompleteCallback(WriteCompleteCallback&& cb)  
  2102.         { writeCompleteCallback_ = cb; }  
  2103.         #endif
  2104. private:  
  2105. void newConnection(int sockfd);  
  2106. void removeConnection(const TcpConnectionPtr& conn);  
  2107.         EventLoop* loop_;  
  2108.         ConnectorPtr connector_; // avoid revealing Connector
  2109. const string name_;  
  2110.         ConnectionCallback connectionCallback_;  
  2111.         MessageCallback messageCallback_;  
  2112.         WriteCompleteCallback writeCompleteCallback_;  
  2113. bool retry_;   // atmoic
  2114. bool connect_; // atomic
  2115. int nextConnId_;  
  2116. mutable MutexLock mutex_;  
  2117.         TcpConnectionPtr connection_; // @BuardedBy mutex_
  2118. };  
  2119. namespace detail  
  2120. {  
  2121. void removeConnection(EventLoop* loop, const TcpConnectionPtr& conn)  
  2122.     {  
  2123.       loop->queueInLoop(boost::bind(&TcpConnection::connectDestroyed, conn));  
  2124.     }  
  2125. void removeConnector(const ConnectorPtr& connector)  
  2126.     {  
  2127. //connector->
  2128.     }  
  2129. }  
  2130. TcpClient::TcpClient(EventLoop* loop,  
  2131. const InetAddress& serverAddr,  
  2132. const string& name)  
  2133.   : loop_(CHECK_NOTNULL(loop)),  
  2134.     connector_(new Connector(loop, serverAddr)),  
  2135.     name_(name),  
  2136.     connectionCallback_(defaultConnectionCallback),  
  2137.     messageCallback_(defaultMessageCallback),  
  2138.     retry_(false),  
  2139.     connect_(true),  
  2140.     nextConnId_(1)  
  2141. {  
  2142.     connector_->setNewConnectionCallback(  
  2143.       boost::bind(&TcpClient::newConnection, this, _1));  
  2144. }  
  2145. TcpClient::~TcpClient()  
  2146. {  
  2147.     TcpConnectionPtr conn;  
  2148.     {  
  2149.         MutexLockGuard lock(mutex_);  
  2150.         conn = connection_;  
  2151.     }  
  2152. if (conn)  
  2153.     {  
  2154.         CloseCallback cb = boost::bind(&detail::removeConnection, loop_, _1);  
  2155.         loop_->runInLoop(  
  2156.             boost::bind(&TcpConnection::setCloseCallback, conn, cb));  
  2157.     }  
  2158. else
  2159.     {  
  2160.         connector_->stop();  
  2161.         loop_->runAfter(1, boost::bind(&detail::removeConnector, connector_));  
  2162.     }  
  2163. }  
  2164. void TcpClient::connect()  
  2165. {  
  2166.     connect_ = true;  
  2167.     connector_->start();  
  2168. }  
  2169. void TcpClient::disconnect()  
  2170. {  
  2171.     connect_ = false;  
  2172.     {  
  2173.         MutexLockGuard lock(mutex_);  
  2174. if (connection_)  
  2175.         {  
  2176.             connection_->shutdown();  
  2177.         }  
  2178.     }  
  2179. }  
  2180. void TcpClient::stop()  
  2181. {  
  2182.     connect_ = false;  
  2183.     connector_->stop();  
  2184. }  
  2185. void TcpClient::newConnection(int sockfd)  
  2186. {  
  2187.     loop_->assertInLoopThread();  
  2188.     InetAddress peerAddr(sockets::getPeerAddr(sockfd));  
  2189. char buf[32];  
  2190.     snprintf(buf, sizeof buf, ":%s#%d", peerAddr.toIpPort().c_str(), nextConnId_);  
  2191.     ++nextConnId_;  
  2192.     string connName = name_ + buf;  
  2193.     InetAddress localAddr(sockets::getLocalAddr(sockfd));  
  2194.     TcpConnectionPtr conn(new TcpConnection(loop_,  
  2195.                                           connName,  
  2196.                                           sockfd,  
  2197.                                           localAddr,  
  2198.                                           peerAddr));  
  2199.     conn->setConnectionCallback(connectionCallback_);  
  2200.     conn->setMessageCallback(messageCallback_);  
  2201.     conn->setWriteCompleteCallback(writeCompleteCallback_);  
  2202.     conn->setCloseCallback(  
  2203.       boost::bind(&TcpClient::removeConnection, this, _1)); // FIXME: unsafe
  2204.     {  
  2205.         MutexLockGuard lock(mutex_);  
  2206.         connection_ = conn;  
  2207.     }  
  2208.     conn->connectEstablished();  
  2209. }  
  2210. void TcpClient::removeConnection(const TcpConnectionPtr& conn)  
  2211. {  
  2212.     loop_->assertInLoopThread();  
  2213.     assert(loop_ == conn->getLoop());  
  2214.     {  
  2215.         MutexLockGuard lock(mutex_);  
  2216.         assert(connection_ == conn);  
  2217.         connection_.reset();  
  2218.     }  
  2219.     loop_->queueInLoop(boost::bind(&TcpConnection::connectDestroyed, conn));  
  2220. if (retry_ && connect_)  
  2221.     {  
  2222.         connector_->restart();  
  2223.     }  
  2224. }  
  2225. /*
  2226.  *Epoll
  2227.  */
  2228. class Epoller:noncopyable{  
  2229. public:  
  2230. typedef vector<Channel*> ChannelList;  
  2231.         Epoller(EventLoop* loop)  
  2232.             :ownerLoop_(loop),  
  2233.             epollfd_(::epoll_create1(EPOLL_CLOEXEC)),  
  2234.             events_(kInitEventListSize)  
  2235.         {  
  2236. if(epollfd_<0){  
  2237.                 printf("Epoller::epoll_create1() error\n");  
  2238.                 abort();  
  2239.             }  
  2240.         }  
  2241.         ~Epoller(){  
  2242.             ::close(epollfd_);  
  2243.         }  
  2244.         Timestamp poll(int timeoutMs,ChannelList* activeChannels){  
  2245. int numEvents=::epoll_wait(epollfd_,&*events_.begin(),  
  2246. static_cast<int>(events_.size()),timeoutMs);  
  2247.             Timestamp now(Timestamp::now());  
  2248. if(numEvents>0){  
  2249.                 fillActiveChannels(numEvents,activeChannels);  
  2250. if(implicit_cast<size_t>(numEvents)==events_.size()){  
  2251.                     events_.resize(events_.size()*2);  
  2252.                 }  
  2253. else if(numEvents==0){}  
  2254. else{  
  2255.                     printf("Epoller::epoll_wait() error\n");  
  2256.                 }  
  2257.             }  
  2258. return now;  
  2259.         }  
  2260. void updateChannel(Channel* channel){  
  2261.             assertInLoopThread();  
  2262. const int index=channel->index();  
  2263. if(index==-1||index==2){  
  2264. int fd=channel->fd();  
  2265. if(index==-1){  
  2266.                     assert(channels_.find(fd)==channels_.end());  
  2267.                     channels_[fd]=channel;  
  2268.                 }  
  2269. else{  
  2270.                     assert(channels_.find(fd)!=channels_.end());  
  2271.                     assert(channels_[fd]==channel);  
  2272.                 }  
  2273.                 channel->set_index(1);  
  2274.                 update(EPOLL_CTL_ADD,channel);  
  2275.             }  
  2276. else{  
  2277. int fd=channel->fd();  
  2278.                 (void)fd;  
  2279.                 assert(channels_.find(fd)!=channels_.end());  
  2280.                 assert(channels_[fd]==channel);  
  2281.                 assert(index==1);  
  2282. if(channel->isNoneEvent()){  
  2283.                     update(EPOLL_CTL_DEL,channel);  
  2284.                     channel->set_index(2);  
  2285.                 }  
  2286. else{  
  2287.                     update(EPOLL_CTL_MOD,channel);  
  2288.                 }  
  2289.             }  
  2290.         }  
  2291. void removeChannel(Channel* channel){  
  2292.             assertInLoopThread();  
  2293. int fd=channel->fd();  
  2294.             assert(channels_.find(fd)!=channels_.end());  
  2295.             assert(channels_[fd]==channel);  
  2296.             assert(channel->isNoneEvent());  
  2297. int index=channel->index();  
  2298.             assert(index==1||index==2);  
  2299. size_t n=channels_.erase(fd);  
  2300.             (void)n;  
  2301.             assert(n==1);  
  2302. if(index==1){  
  2303.                 update(EPOLL_CTL_DEL,channel);  
  2304.             }  
  2305.             channel->set_index(-1);  
  2306.         }  
  2307. void assertInLoopThread(){  
  2308.             ownerLoop_->assertInLoopThread();  
  2309.         }  
  2310. private:  
  2311. static const int kInitEventListSize=16;  
  2312. void fillActiveChannels(int numEvents,ChannelList* activeChannels) const
  2313.         {  
  2314.             assert(implicit_cast<size_t>(numEvents)<=events_.size());  
  2315. for(int i=0;i<numEvents;i++){  
  2316.                 Channel* channel=static_cast<Channel*>(events_[i].data.ptr);  
  2317. int fd=channel->fd();  
  2318.                 ChannelMap::const_iterator it=channels_.find(fd);  
  2319.                 assert(it!=channels_.end());  
  2320.                 assert(it->second==channel);  
  2321.                 channel->set_revents(events_[i].events);  
  2322.                 activeChannels->push_back(channel);  
  2323.             }  
  2324.         }  
  2325. void update(int operation,Channel* channel){  
  2326. struct epoll_event event;  
  2327.             bzero(&event,sizeof event);  
  2328.             event.events=channel->events();  
  2329.             event.data.ptr=channel;  
  2330. int fd=channel->fd();  
  2331. if(::epoll_ctl(epollfd_,operation,fd,&event)<0){  
  2332. if(operation==EPOLL_CTL_DEL){  
  2333.                     printf("Epoller::update() EPOLL_CTL_DEL error\n");  
  2334.                 }  
  2335. else{  
  2336.                     printf("Epoller::update() EPOLL_CTL_ error\n");  
  2337.                 }  
  2338.             }  
  2339.         }  
  2340. typedef vector<struct epoll_event> EventList;  
  2341. typedef map<int,Channel*> ChannelMap;  
  2342.         EventLoop* ownerLoop_;  
  2343. int epollfd_;  
  2344.         EventList events_;  
  2345.         ChannelMap channels_;  
  2346. };  
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年06月26日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文字部分:
  • 代码部分:
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档