Acceptor类用于创建套接字,设置套接字选项,调用listen函数,接受连接,然后调用TcpServer的回调。
// Copyright 2010, Shuo Chen. All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#include "muduo/net/Acceptor.h"
#include "muduo/base/Logging.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/InetAddress.h"
#include "muduo/net/SocketsOps.h"
#include
#include
//#include
//#include
#include
using namespace muduo;
using namespace muduo::net;
Acceptor::Acceptor(EventLoop* loop, const InetAddress& listenAddr, bool reuseport)
: loop_(loop), //本线程的loop
acceptSocket_(sockets::create NonblockingOrDie(listenAddr.family())),//初始化创建sockt fd
acceptChannel_(loop, acceptSocket_.fd()),//初始化channel
listenning_(false), //是否处于监听状态
idleFd_(::open("/dev/null", O_RDONLY | O_CLOEXEC))
{
assert(idleFd_ >= 0);
acceptSocket_.setReuseAddr(true); //设置端口可重用
acceptSocket_.setReusePort(reuseport); //设置地址可重用
acceptSocket_.bindAddress(listenAddr); //bind函数的封装
acceptChannel_.setReadCallback(
std::bind(&Acceptor::handleRead, this));// //有可读事件,当fd可读时调用回调函数hanleRead
}
Acceptor::~Acceptor()
{
acceptChannel_.disableAll();//将其冲poller监听集合中移除,此时为kDeleted状态
acceptChannel_.remove();//将其从EventList events_中移除,此时为kNew状态
::close(idleFd_);
}
void Acceptor::listen()
{
loop_->assertInLoopThread(); //保证是在IO线程
listenning_ = true;
acceptSocket_.listen();
acceptChannel_.enableReading(); ////注册可读事件
}
void Acceptor::handleRead() //新连接到达由acccptor处理
{
loop_->assertInLoopThread();
InetAddress peerAddr;
//FIXME loop until no more
int connfd = acceptSocket_.accept(&peerAddr);//这里时真正接收连接
if (connfd >= 0)
{
// string hostport = peerAddr.toIpPort();
// LOG_TRACE << "Accepts of " << hostport;
if (newConnectionCallback_)
{
newConnectionCallback_(connfd, peerAddr);//将新连接信息传送到回调函数中
}
else//没有回调函数则关闭client对应的fd
{
sockets::close(connfd);
}
}
else
{
LOG_SYSERR << "in Acceptor::handleRead";
// Read the section named "The special problem of
// accept()ing when you can't" in libev's doc.
// By Marc Lehmann, author of libev.
if (errno == EMFILE)
{
::close(idleFd_);
idleFd_ = ::accept(acceptSocket_.fd(), NULL, NULL);
::close(idleFd_);
idleFd_ = ::open("/dev/null", O_RDONLY | O_CLOEXEC);
}
}
}
比较容易理解,不多说