1e254a845SShuo Chen// excerpts from http://code.google.com/p/muduo/ 2e254a845SShuo Chen// 3e254a845SShuo Chen// Use of this source code is governed by a BSD-style license 4e254a845SShuo Chen// that can be found in the License file. 5e254a845SShuo Chen// 6e254a845SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 7e254a845SShuo Chen 8e254a845SShuo Chen#include "Acceptor.h" 9e254a845SShuo Chen 10e254a845SShuo Chen#include "logging/Logging.h" 11e254a845SShuo Chen#include "EventLoop.h" 12e254a845SShuo Chen#include "InetAddress.h" 13e254a845SShuo Chen#include "SocketsOps.h" 14e254a845SShuo Chen 15e254a845SShuo Chen#include <boost/bind.hpp> 16e254a845SShuo Chen 17e254a845SShuo Chenusing namespace muduo; 18e254a845SShuo Chen 19e254a845SShuo ChenAcceptor::Acceptor(EventLoop* loop, const InetAddress& listenAddr) 20e254a845SShuo Chen : loop_(loop), 21e254a845SShuo Chen acceptSocket_(sockets::createNonblockingOrDie()), 22e254a845SShuo Chen acceptChannel_(loop, acceptSocket_.fd()), 23e254a845SShuo Chen listenning_(false) 24e254a845SShuo Chen{ 25e254a845SShuo Chen acceptSocket_.setReuseAddr(true); 26e254a845SShuo Chen acceptSocket_.bindAddress(listenAddr); 27e254a845SShuo Chen acceptChannel_.setReadCallback( 28e254a845SShuo Chen boost::bind(&Acceptor::handleRead, this)); 29e254a845SShuo Chen} 30e254a845SShuo Chen 31e254a845SShuo Chenvoid Acceptor::listen() 32e254a845SShuo Chen{ 33e254a845SShuo Chen loop_->assertInLoopThread(); 34e254a845SShuo Chen listenning_ = true; 35e254a845SShuo Chen acceptSocket_.listen(); 36e254a845SShuo Chen acceptChannel_.enableReading(); 37e254a845SShuo Chen} 38e254a845SShuo Chen 39e254a845SShuo Chenvoid Acceptor::handleRead() 40e254a845SShuo Chen{ 41e254a845SShuo Chen loop_->assertInLoopThread(); 42e254a845SShuo Chen InetAddress peerAddr(0); 43e254a845SShuo Chen //FIXME loop until no more 44e254a845SShuo Chen int connfd = acceptSocket_.accept(&peerAddr); 45e254a845SShuo Chen if (connfd >= 0) { 46e254a845SShuo Chen if (newConnectionCallback_) { 47e254a845SShuo Chen newConnectionCallback_(connfd, peerAddr); 48e254a845SShuo Chen } else { 49e254a845SShuo Chen sockets::close(connfd); 50e254a845SShuo Chen } 51e254a845SShuo Chen } 52e254a845SShuo Chen} 53e254a845SShuo Chen 54