140161064SShuo Chen// excerpts from http://code.google.com/p/muduo/
240161064SShuo Chen//
340161064SShuo Chen// Use of this source code is governed by a BSD-style license
440161064SShuo Chen// that can be found in the License file.
540161064SShuo Chen//
640161064SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
740161064SShuo Chen
840161064SShuo Chen#include "Acceptor.h"
940161064SShuo Chen
1040161064SShuo Chen#include "logging/Logging.h"
1140161064SShuo Chen#include "EventLoop.h"
1240161064SShuo Chen#include "InetAddress.h"
1340161064SShuo Chen#include "SocketsOps.h"
1440161064SShuo Chen
1540161064SShuo Chen#include <boost/bind.hpp>
1640161064SShuo Chen
1740161064SShuo Chenusing namespace muduo;
1840161064SShuo Chen
1940161064SShuo ChenAcceptor::Acceptor(EventLoop* loop, const InetAddress& listenAddr)
2040161064SShuo Chen  : loop_(loop),
2140161064SShuo Chen    acceptSocket_(sockets::createNonblockingOrDie()),
2240161064SShuo Chen    acceptChannel_(loop, acceptSocket_.fd()),
2340161064SShuo Chen    listenning_(false)
2440161064SShuo Chen{
2540161064SShuo Chen  acceptSocket_.setReuseAddr(true);
2640161064SShuo Chen  acceptSocket_.bindAddress(listenAddr);
2740161064SShuo Chen  acceptChannel_.setReadCallback(
2840161064SShuo Chen      boost::bind(&Acceptor::handleRead, this));
2940161064SShuo Chen}
3040161064SShuo Chen
3140161064SShuo Chenvoid Acceptor::listen()
3240161064SShuo Chen{
3340161064SShuo Chen  loop_->assertInLoopThread();
3440161064SShuo Chen  listenning_ = true;
3540161064SShuo Chen  acceptSocket_.listen();
3640161064SShuo Chen  acceptChannel_.enableReading();
3740161064SShuo Chen}
3840161064SShuo Chen
3940161064SShuo Chenvoid Acceptor::handleRead()
4040161064SShuo Chen{
4140161064SShuo Chen  loop_->assertInLoopThread();
4240161064SShuo Chen  InetAddress peerAddr(0);
4340161064SShuo Chen  //FIXME loop until no more
4440161064SShuo Chen  int connfd = acceptSocket_.accept(&peerAddr);
4540161064SShuo Chen  if (connfd >= 0) {
4640161064SShuo Chen    if (newConnectionCallback_) {
4740161064SShuo Chen      newConnectionCallback_(connfd, peerAddr);
4840161064SShuo Chen    } else {
4940161064SShuo Chen      sockets::close(connfd);
5040161064SShuo Chen    }
5140161064SShuo Chen  }
5240161064SShuo Chen}
5340161064SShuo Chen
54