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