muduo之Acceptor

         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 <errno.h>
#include <fcntl.h>
//#include <sys/types.h>
//#include <sys/stat.h>
#include <unistd.h>

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);
    }
  }
}

       比较容易理解,不多说

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盼盼编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值