19a1e991dSShuo Chen// excerpts from http://code.google.com/p/muduo/ 29a1e991dSShuo Chen// 39a1e991dSShuo Chen// Use of this source code is governed by a BSD-style license 49a1e991dSShuo Chen// that can be found in the License file. 59a1e991dSShuo Chen// 69a1e991dSShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 79a1e991dSShuo Chen 89a1e991dSShuo Chen#include "Acceptor.h" 99a1e991dSShuo Chen 109a1e991dSShuo Chen#include "logging/Logging.h" 119a1e991dSShuo Chen#include "EventLoop.h" 129a1e991dSShuo Chen#include "InetAddress.h" 139a1e991dSShuo Chen#include "SocketsOps.h" 149a1e991dSShuo Chen 159a1e991dSShuo Chen#include <boost/bind.hpp> 169a1e991dSShuo Chen 179a1e991dSShuo Chenusing namespace muduo; 189a1e991dSShuo Chen 199a1e991dSShuo ChenAcceptor::Acceptor(EventLoop* loop, const InetAddress& listenAddr) 209a1e991dSShuo Chen : loop_(loop), 219a1e991dSShuo Chen acceptSocket_(sockets::createNonblockingOrDie()), 229a1e991dSShuo Chen acceptChannel_(loop, acceptSocket_.fd()), 239a1e991dSShuo Chen listenning_(false) 249a1e991dSShuo Chen{ 259a1e991dSShuo Chen acceptSocket_.setReuseAddr(true); 269a1e991dSShuo Chen acceptSocket_.bindAddress(listenAddr); 279a1e991dSShuo Chen acceptChannel_.setReadCallback( 289a1e991dSShuo Chen boost::bind(&Acceptor::handleRead, this)); 299a1e991dSShuo Chen} 309a1e991dSShuo Chen 319a1e991dSShuo Chenvoid Acceptor::listen() 329a1e991dSShuo Chen{ 339a1e991dSShuo Chen loop_->assertInLoopThread(); 349a1e991dSShuo Chen listenning_ = true; 359a1e991dSShuo Chen acceptSocket_.listen(); 369a1e991dSShuo Chen acceptChannel_.enableReading(); 379a1e991dSShuo Chen} 389a1e991dSShuo Chen 399a1e991dSShuo Chenvoid Acceptor::handleRead() 409a1e991dSShuo Chen{ 419a1e991dSShuo Chen loop_->assertInLoopThread(); 429a1e991dSShuo Chen InetAddress peerAddr(0); 439a1e991dSShuo Chen //FIXME loop until no more 449a1e991dSShuo Chen int connfd = acceptSocket_.accept(&peerAddr); 45b4a5ce52SShuo Chen if (connfd >= 0) { 46b4a5ce52SShuo Chen if (newConnectionCallback_) { 479a1e991dSShuo Chen newConnectionCallback_(connfd, peerAddr); 48b4a5ce52SShuo Chen } else { 499a1e991dSShuo Chen sockets::close(connfd); 509a1e991dSShuo Chen } 519a1e991dSShuo Chen } 529a1e991dSShuo Chen} 539a1e991dSShuo Chen 54