提前声明了Acceptor,EventLoop和EventLoopThreadPool。
EventLoop* loop_; // the acceptor loop const string ipPort_; // const string name_; std::unique_ptr acceptor_; // avoid revealing Acceptor 指向acceptor的指针。 std::shared_ptrthreadPool_; ConnectionCallback connectionCallback_; MessageCallback messageCallback_; WriteCompleteCallback writeCompleteCallback_; ThreadInitCallback threadInitCallback_; AtomicInt32 started_; // always in loop thread int nextConnId_; ConnectionMap connections_;
拥有指向acceptor的指针,指向线程池的指针,Connection回调函数,信息回调函数。写完成回调函数,线程初始化回调函数。开始标志位。
初始化函数TcpServer::TcpServer(EventLoop* loop,
const InetAddress& listenAddr,
const string& nameArg,
Option option)
: loop_(CHECK_NOTNULL(loop)), //初始化loop
ipPort_(listenAddr.toIpPort()), //需要一个地址IP
name_(nameArg),
acceptor_(new Acceptor(loop, listenAddr, option == kReusePort)), //new出Acceptor,绑定为本loop。
threadPool_(new EventLoopThreadPool(loop, name_)), //new出线程池
connectionCallback_(defaultConnectionCallback),
messageCallback_(defaultMessageCallback),
nextConnId_(1)
{
acceptor_->setNewConnectionCallback(
std::bind(&TcpServer::newConnection, this, _1, _2));
} //把acceptor的获取NewConnection回调函数设置为TCPServer的
TcpServer::newConnection(int sockfd, const InetAddress& peerAddr)
Acceptor发生可读事件的时候就会被调用。
这个由管理Acceptor的子线程调用。
首先从线程池中获取一个ioLoop。
用ioLoop、connName(创建的TCP连接名字)、文件描述符、本地的地址和peerAddr(参数)。然后设置这个TCP connection的各个回调函数。
最后ioLoop绑定TCP的connectEstablished函数。



