12a18e699SShuo Chen// excerpts from http://code.google.com/p/muduo/ 22a18e699SShuo Chen// 32a18e699SShuo Chen// Use of this source code is governed by a BSD-style license 42a18e699SShuo Chen// that can be found in the License file. 52a18e699SShuo Chen// 62a18e699SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 72a18e699SShuo Chen 82a18e699SShuo Chen#include "Acceptor.h" 92a18e699SShuo Chen 102a18e699SShuo Chen#include "logging/Logging.h" 112a18e699SShuo Chen#include "EventLoop.h" 122a18e699SShuo Chen#include "InetAddress.h" 132a18e699SShuo Chen#include "SocketsOps.h" 142a18e699SShuo Chen 152a18e699SShuo Chen#include <boost/bind.hpp> 162a18e699SShuo Chen 172a18e699SShuo Chenusing namespace muduo; 182a18e699SShuo Chen 192a18e699SShuo ChenAcceptor::Acceptor(EventLoop* loop, const InetAddress& listenAddr) 202a18e699SShuo Chen : loop_(loop), 212a18e699SShuo Chen acceptSocket_(sockets::createNonblockingOrDie()), 222a18e699SShuo Chen acceptChannel_(loop, acceptSocket_.fd()), 232a18e699SShuo Chen listenning_(false) 242a18e699SShuo Chen{ 252a18e699SShuo Chen acceptSocket_.setReuseAddr(true); 262a18e699SShuo Chen acceptSocket_.bindAddress(listenAddr); 272a18e699SShuo Chen acceptChannel_.setReadCallback( 282a18e699SShuo Chen boost::bind(&Acceptor::handleRead, this)); 292a18e699SShuo Chen} 302a18e699SShuo Chen 312a18e699SShuo Chenvoid Acceptor::listen() 322a18e699SShuo Chen{ 332a18e699SShuo Chen loop_->assertInLoopThread(); 342a18e699SShuo Chen listenning_ = true; 352a18e699SShuo Chen acceptSocket_.listen(); 362a18e699SShuo Chen acceptChannel_.enableReading(); 372a18e699SShuo Chen} 382a18e699SShuo Chen 392a18e699SShuo Chenvoid Acceptor::handleRead() 402a18e699SShuo Chen{ 412a18e699SShuo Chen loop_->assertInLoopThread(); 422a18e699SShuo Chen InetAddress peerAddr(0); 432a18e699SShuo Chen //FIXME loop until no more 442a18e699SShuo Chen int connfd = acceptSocket_.accept(&peerAddr); 45b4a5ce52SShuo Chen if (connfd >= 0) { 46b4a5ce52SShuo Chen if (newConnectionCallback_) { 472a18e699SShuo Chen newConnectionCallback_(connfd, peerAddr); 48b4a5ce52SShuo Chen } else { 492a18e699SShuo Chen sockets::close(connfd); 502a18e699SShuo Chen } 512a18e699SShuo Chen } 522a18e699SShuo Chen} 532a18e699SShuo Chen 54