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