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