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