Acceptor.cc revision 354280cf
1354280cfSShuo Chen// excerpts from http://code.google.com/p/muduo/ 2354280cfSShuo Chen// 3354280cfSShuo Chen// Use of this source code is governed by a BSD-style license 4354280cfSShuo Chen// that can be found in the License file. 5354280cfSShuo Chen// 6354280cfSShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 7354280cfSShuo Chen 8354280cfSShuo Chen#include "Acceptor.h" 9354280cfSShuo Chen 10354280cfSShuo Chen#include "logging/Logging.h" 11354280cfSShuo Chen#include "EventLoop.h" 12354280cfSShuo Chen#include "InetAddress.h" 13354280cfSShuo Chen#include "SocketsOps.h" 14354280cfSShuo Chen 15354280cfSShuo Chen#include <boost/bind.hpp> 16354280cfSShuo Chen 17354280cfSShuo Chenusing namespace muduo; 18354280cfSShuo Chen 19354280cfSShuo ChenAcceptor::Acceptor(EventLoop* loop, const InetAddress& listenAddr) 20354280cfSShuo Chen : loop_(loop), 21354280cfSShuo Chen acceptSocket_(sockets::createNonblockingOrDie()), 22354280cfSShuo Chen acceptChannel_(loop, acceptSocket_.fd()), 23354280cfSShuo Chen listenning_(false) 24354280cfSShuo Chen{ 25354280cfSShuo Chen acceptSocket_.setReuseAddr(true); 26354280cfSShuo Chen acceptSocket_.bindAddress(listenAddr); 27354280cfSShuo Chen acceptChannel_.setReadCallback( 28354280cfSShuo Chen boost::bind(&Acceptor::handleRead, this)); 29354280cfSShuo Chen} 30354280cfSShuo Chen 31354280cfSShuo Chenvoid Acceptor::listen() 32354280cfSShuo Chen{ 33354280cfSShuo Chen loop_->assertInLoopThread(); 34354280cfSShuo Chen listenning_ = true; 35354280cfSShuo Chen acceptSocket_.listen(); 36354280cfSShuo Chen acceptChannel_.enableReading(); 37354280cfSShuo Chen} 38354280cfSShuo Chen 39354280cfSShuo Chenvoid Acceptor::handleRead() 40354280cfSShuo Chen{ 41354280cfSShuo Chen loop_->assertInLoopThread(); 42354280cfSShuo Chen InetAddress peerAddr(0); 43354280cfSShuo Chen //FIXME loop until no more 44354280cfSShuo Chen int connfd = acceptSocket_.accept(&peerAddr); 45354280cfSShuo Chen if (connfd >= 0) { 46354280cfSShuo Chen if (newConnectionCallback_) { 47354280cfSShuo Chen newConnectionCallback_(connfd, peerAddr); 48354280cfSShuo Chen } else { 49354280cfSShuo Chen sockets::close(connfd); 50354280cfSShuo Chen } 51354280cfSShuo Chen } 52354280cfSShuo Chen} 53354280cfSShuo Chen 54